多态性协会在同一个模型的多个关联
-
19-09-2019 - |
题
我稍微感到困惑多态关联我已经得到了。我需要一个文章模型有一个标题图片,许多图像,但我希望有一个单一的图像模型。为了使事情更加混乱,图像模型是多态的(以允许其他资源,有许多图像)。
我用这个关联在我的文章模型:
class Article < ActiveRecord::Base
has_one :header_image, :as => :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的不能区分。
不隶属于 StackOverflow