与同型号的多个关联多态性协会
我略有困惑我有一个多态关联。我需要一个第三模型有一个头形象,和许多图像,但我希望有一个单一的图像模型。为了使事情更加混乱,图像模型是多态(允许其他资源有许多图像)。
I'm slightly confused about a polymorphic association I've got. I need an Article model to have a header image, and many images, but I want to have a single Image model. To make matters even more confusing, the Image model is polymorphic (to allow other resources to have many images).
我用在我的文章模型这种关联:
I'm using this association in my Article model:
class Article < ActiveRecord::Base
has_one :header_image, :as => :imageable
has_many :images, :as => :imageable
end
这可能吗?谢谢你。
Is this possible? Thanks.
是的。这是完全可能的。
Yep. That's totally possible.
您可能需要指定 header_image
类的名称,因为它无法推断。包括:依赖=&GT; :破坏
太,以确保如果该制品被去除的图像被破坏
You might need to specify the class name for header_image
, as it can't be inferred. Include :dependent => :destroy
too, to ensure that the images are destroyed if the article is removed
class Article < ActiveRecord::Base
has_one :header_image, :as => :imageable, :class_name => 'Image', :dependent => :destroy
has_many :images, :as => :imageable, :dependent => :destroy
end
然后在另一端...
then on the other end...
class Image < ActiveRecord::Base
belongs_to :imageable, :polymorphic => true
end