多态关联在同一模型上具有多个关联

我对我所获得的多态关联感到有些困惑。 我需要一个文章模型来获得标题图像和许多图像,但我希望有一个图像模型。 更令人困惑的是,Image模型具有多态性(允许其他资源拥有许多图像)。

我在我的文章模型中使用此关联:

class Article  :imageable has_many :images, :as => :imageable end 

这可能吗? 谢谢。

是的。 这完全有可能。

您可能需要为header_image指定类名,因为无法推断它。 包括:dependent => :destroy ,以确保在删除文章时销毁图像

 class Article < ActiveRecord::Base has_one :header_image, :as => :imageable, :class_name => 'Image', :dependent => :destroy has_many :images, :as => :imageable, :dependent => :destroy end 

然后在另一端……

 class Image < ActiveRecord::Base belongs_to :imageable, :polymorphic => true end 

我尝试了这个,但随后header_image返回其中一个图像。 仅仅因为图像表没有指定不同的图像使用类型(header_image与普通图像)。 它简单地说:imageable_type =两种用途的图像。 因此,如果没有存储有关使用类型的信息,则ActiveRecord无法区分。