同一模型上具有多个关联的多态关联 [英] Polymorphic Association with multiple associations on the same model

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

问题描述

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

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

这可能吗?谢谢.

推荐答案

是的.这完全有可能.

您可能需要为 header_image 指定类名,因为它无法推断.包括 :dependent =>:destroy 也是,以确保如果文章被删除,图像也会被销毁

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

然后在另一端...

class Image < ActiveRecord::Base
  belongs_to :imageable, :polymorphic => true
end

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

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