繁体   English   中英

rails has_one of has_many association

[英]rails has_one of a has_many association

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

我知道这对模型中的方法很容易,但我希望它是一个关联,以便我可以使用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”的布尔列,它将图像关联为“主要”图像。

我考虑过这样做的方法之一是将一个main_image_id列添加到products表中,然后添加到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字段,然后为将来的产品添加验证以确保添加了主图像?

编辑:

我应该使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM