与同型号的多个关联多态性协会 [英] Polymorphic Association with multiple associations on the same model

查看:141
本文介绍了与同型号的多个关联多态性协会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我略有困惑我有一个多态关联。我需要一个第三模型有一个头形象,和许多图像,但我希望有一个单一的图像模型。为了使事情更加混乱,图像模型是多态(允许其他资源有许多图像)。

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

这篇关于与同型号的多个关联多态性协会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆