我在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
模型不知道图片和cover_image之间的区别,并且每个图片都存储在
#<Image ... imageable_id: 17, imageable_type: "Place">
我正在考虑添加一imageable_sub_type
列以Image
存储子类型。.所以我的图像看起来像:
#<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
。
通过在关系中添加条件,可以在调用时检索images
with 。添加图像时,它不会为您设置属性。当基于视图的某些输入(例如复选框标签)添加图像时,必须单独完成此操作。imageable_sub_type = cover_image
place.cover_image
更新:您可以覆盖默认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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句