【问题标题】:Polymorphic Association with multiple associations on the same model同一模型上具有多个关联的多态关联
【发布时间】:2009-07-22 20:29:31
【问题描述】:

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

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

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

这可能吗?谢谢。

【问题讨论】:

标签: ruby-on-rails ruby activerecord polymorphic-associations


【解决方案1】:

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

【讨论】:

  • 你需要单表继承
【解决方案2】:

是的。这是完全可能的。

您可能需要为header_image 指定类名,因为它无法推断。也包括:dependent =&gt; :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

【讨论】:

猜你喜欢
  • 2011-01-30
  • 1970-01-01
  • 1970-01-01
  • 2013-08-29
  • 2020-05-14
  • 1970-01-01
  • 2012-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多