rails has_one of has_many association

Ste*_*ose 15 activerecord model ruby-on-rails polymorphic-associations

我有一个产品,一个产品可以有很多图像.这是通过关联表.但是,我想要一个产品有一个主图像.

我知道这对模型中的方法很容易,但我希望它是一个关联,以便我可以使用在查询中预加载它include.

楷模:

class Product < ActiveRecord::Base
    has_many :image_associations, :as => :imageable
    has_many :images, :through => :image_associations
end

class ImageAssociation < ActiveRecord::Base
    belongs_to :image
    belongs_to :imageable, :polymorphic => true
end

class Image < ActiveRecord::Base
    has_many :image_associations
end
Run Code Online (Sandbox Code Playgroud)

在ImageAssociation表中,有一个名为"feature"的布尔列,它将图像关联为"主要"图像.

我考虑过这样做的一种方法是main_image_id在products表中添加一列,然后添加到Image模型中:

belongs_to :image, :class => "Image", :foreign_key => "main_image_id"
Run Code Online (Sandbox Code Playgroud)

但是,如果主图像为零,则不允许任何回退到其他has_many图像 - 我希望加载关联.

这就是为什么我希望图像模型中的某些东西像:

has_one :image, :through => :images, :conditions => 'feature = true', :order => 'created_at DESC'
Run Code Online (Sandbox Code Playgroud)

但这给了我一个关联错误.

有没有什么方法可以编辑has_one,或者我是否真的需要运行rake任务将图像推送到每个main_image_id字段,然后为将来的产品添加验证以确保添加了主图像?

编辑:

我应该使用has_and_belongs_to_many协会吗?

Cho*_*ett 14

我想,你几乎就在那里,虽然我对多态关联并不是那么清楚.我想你想要以下内容:

has_one :main_image_assoc, class => "ImageAssociation", :conditions => 'feature = true', :order => 'created_at DESC', :as => :imageable
has_one :image, :through => :main_image_assoc
Run Code Online (Sandbox Code Playgroud)