【发布时间】:2012-03-23 13:38:02
【问题描述】:
我有一个产品,一个产品可以有很多图像。这是通过关联表实现的。但是,我希望产品有一个主图像。
我知道使用模型中的方法很容易做到这一点,但我希望它是一个关联,以便我可以使用 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 表中,有一个名为“特征”的布尔列,它将图像关联为“主”图像。
我考虑过的其中一种方法是将main_image_id 列添加到产品表中,然后添加到Image 模型中:
belongs_to :image, :class => "Image", :foreign_key => "main_image_id"
但是,如果主图像为 nil,则这不允许任何回退到其他 has_many 图像——我希望加载关联。
这就是为什么我希望图像模型中有一些东西,例如:
has_one :image, :through => :images, :conditions => 'feature = true', :order => 'created_at DESC'
但这给了我一个关联错误。
有什么方法可以编辑 has_one,还是我真的需要运行 rake 任务将图像推送到每个 main_image_id 字段,然后为未来的产品添加验证以确保已添加主图像?
编辑:
我应该改用has_and_belongs_to_many 关联吗?
【问题讨论】:
标签: ruby-on-rails activerecord model polymorphic-associations