我有一个产品,一个产品可以有很多图片。这是通过关联表。但是,我希望产品具有一个主要图像。
我知道使用模型中的方法很容易做到这一点,但我希望它是一个关联,以便我可以使用 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
在 ImageAssociation 表中,有一个名为“feature”的 bool 列,它将图像关联为“主”图像。
我考虑过这样做的方法之一是添加
main_image_id
列到产品表,然后添加到 Image
模型:belongs_to :image, :class => "Image", :foreign_key => "main_image_id"
但是,如果主图像为零,这不允许回退到其他 has_many 图像——我希望关联加载。
这就是为什么我希望图像模型中有一些东西,例如:
has_one :image, :through => :images, :conditions => 'feature = true', :order => 'created_at DESC'
但这给了我一个关联错误。
有什么方法可以编辑 has_one,还是我真的需要运行 rake 任务将图像推送到每个 main_image_id 字段,然后为 future 的产品添加验证以确保已添加主图像?
编辑:
我应该使用
has_and_belongs_to_many
协会代替?
最佳答案
你快到了,我想,虽然我对多态关联不是很清楚。我想你想要以下内容:
has_one :main_image_assoc, class => "ImageAssociation", :conditions => 'feature = true', :order => 'created_at DESC', :as => :imageable
has_one :image, :through => :main_image_assoc
关于ruby-on-rails - rails has_one 一个 has_many 关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9840169/