9

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

我在我的文章模型中使用了这个关联:

class Article < ActiveRecord::Base
  has_one :header_image, :as => :imageable
  has_many :images, :as => :imageable
end

这可能吗?谢谢。

4

2 回答 2

7

我试过了,但是 header_image 返回了其中一张图像。仅仅是因为图像表没有指定不同的图像使用类型(header_image 与普通图像)。它只是说:imageable_type = 两种用途的图像。因此,如果没有存储有关使用类型的信息,ActiveRecord 就无法区分。

于 2009-11-19T15:31:32.060 回答
4

是的。这是完全可能的。

您可能需要为 指定类名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
于 2009-07-23T00:17:47.127 回答