【发布时间】: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。
【问题讨论】:
-
您是否尝试过您链接的帖子中提供的语法?即
conditions: { imageable_sub_type: 'cover_image' }而不是使用lambda和where? -
是的,但不推荐使用
conditions。但结果还是一样。 -
@TimPetricola 用可能的解决方案更新了答案
标签: ruby-on-rails activerecord polymorphism