【问题标题】:rails has_one of a has_many associationrails has_one has_many 关联
【发布时间】: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


    【解决方案1】:

    我想你快到了,虽然我对多态关联不是很清楚。我认为您想要以下内容:

    has_one :main_image_assoc, class => "ImageAssociation", :conditions => 'feature = true', :order => 'created_at DESC', :as => :imageable
    has_one :image, :through => :main_image_assoc
    

    【讨论】:

    • 不。如果需要,您可以对集合使用其他过滤的 has_many 关联来执行此操作,但不要指定 has_one。出现这个错误:ActiveRecord::HasOneThroughCantAssociateThroughCollection: Cannot have a has_one :through association 'Article#image' where the :through association 'Article#image_associations' is a collection. Specify a has_one or belongs_to association in the :through option instead.已经试过了。
    • 更正第一行-:has_one :main_image_assoc, :class_name =&gt; "ImageAssociation",:order =&gt; 'feature = true', :as =&gt; :imageable ...这允许后备(和正确的语法)。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多