Ruby on rails rails是众多关联中的一个

Ruby on rails rails是众多关联中的一个,ruby-on-rails,activerecord,model,polymorphic-associations,Ruby On Rails,Activerecord,Model,Polymorphic Associations,我有一个产品,一个产品可以有很多图片。这是通过关联表实现的。然而,我希望一个产品有一个主要的形象 我知道使用模型中的方法很容易做到这一点,但我希望它是一个关联,这样我就可以使用include在查询中预加载它 型号: class Product < ActiveRecord::Base has_many :image_associations, :as => :imageable has_many :images, :through => :image_assoc

我有一个产品,一个产品可以有很多图片。这是通过关联表实现的。然而,我希望一个产品有一个主要的形象

我知道使用模型中的方法很容易做到这一点,但我希望它是一个关联,这样我就可以使用
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
但是,如果主映像为nil,则这不允许任何回退到另一个具有多个映像的映像,我希望加载关联

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

has_one :image, :through => :images, :conditions => 'feature = true', :order => 'created_at DESC'
但这给了我一个关联错误

是否有任何方法可以编辑有一个,或者我真的需要运行一个rake任务,将一个图像推送到每个主图像id字段中,然后为将来的产品添加一个验证,以确保主图像已被添加

编辑:


我应该使用一个
has\u和\u属于\u many
关联吗?

我想你就快到了,尽管我对多态关联不是很清楚。我想你想要的是:

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

不。如果需要,您可以使用其他筛选的has\u多个关联为集合执行此操作,但不能指定has\u关联。出现以下错误:
ActiveRecord::HasOneThroughCantAssociateThroughCollection:不能具有has_one:through关联“Article#image”,其中:through关联“Article#image#associations”是一个集合。改为在:through选项中指定一个has_one或belient to关联。
已经尝试过。第一行更正-
:has_one:main_image_assoc,:class_name=>“ImageAssociation”,:order=>“feature=true”,:as=>:imageable
…这允许回退(和正确的语法)。谢谢
has_one :main_image_assoc, class => "ImageAssociation", :conditions => 'feature = true', :order => 'created_at DESC', :as => :imageable
has_one :image, :through => :main_image_assoc