【问题标题】:Multiple polymorphic association on a same model in railsrails中同一模型上的多个多态关联
【发布时间】:2013-09-20 14:26:49
【问题描述】:

我在 Image 模型上有一个多态关联,并且需要在 Place 模型上有两个关联。比如:

class Place < ActiveRecord::Base
  has_many :pictures, as: :imageable, class_name: 'Image'
  has_one :cover_image, as: :imageable, class_name: 'Image'
end

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

这显然是行不通的,Image 模型不知道图片和封面图像之间的区别,并且每个图像都存储有

#<Image ... imageable_id: 17, imageable_type: "Place">

我正在考虑向Image 添加一个imageable_sub_type 列来存储子类型。所以我的图像看起来像:

#<Image ... imageable_id: 17, imageable_type: "Place", imageable_sub_type: "cover_image">

我可以轻松地从Place 中的关联中仅检索具有该子类型的图像:

has_one :cover_image, -> { where(imageable_sub_type: 'cover_image'), as: :imageable, class_name: 'Image'

但是我在将图像添加到Place 时找不到设置此值的方法(实际上它始终设置为nil)。

有没有办法做到这一点?


我尝试这样做:https://stackoverflow.com/a/3078286/1015177 但问题仍然存在,imageable_sub_type 仍然是 nil

【问题讨论】:

标签: ruby-on-rails activerecord polymorphism


【解决方案1】:

在关系上使用条件时,如果您通过关系构建记录(即使用 create_cover_image),它将分配该条件。

如果您希望它在分配 Image 的现有实例时更改 imageable_sub_type 的值,那么您可以覆盖 cover_image= 来做到这一点。即

def cover_image= cover_image
  cover_image.imageable_sub_type = 'cover_image'
  super
end

【讨论】:

  • 谢谢!看起来不错,但我认为我会将控件保留在控制器中以获得更大的灵活性(并且不必为每个模型中与 Image 的每个关系定义方法)
【解决方案2】:

通过在关系中添加条件,它可以让您在调用place.cover_image 时使用imageable_sub_type = cover_image 检索images。添加图像时,它不会为您设置属性。当基于来自视图的某些输入(如复选框标记)添加图像时,必须单独完成。

更新:您可以覆盖默认的 association= 方法,如下所示 Place 模型:

 def cover_image=(img)
     # add the img to tthe associated pictures 
     self.pictures << img 

     # mark current img type as cover
     img.update_attribute(:imageable_sub_type, "cover_image")

     # mark all other images type as nil, this to avoid multiple cover images, 
     Picture.update_all( {:imageable_sub_type => nil}, {:id => (self.pictures-[img])} ) 

 end

【讨论】:

  • 我试图自动化它,但似乎现在有办法做到这一点。所以谢谢你的回答,我会那样做的!
猜你喜欢
  • 2011-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-29
  • 2018-01-05
  • 1970-01-01
  • 2011-05-06
  • 1970-01-01
相关资源
最近更新 更多