我的问题与这个问题基本相同: Polymorphic Association with multiple associations on the same model
但是,正如稍后的评论者所说明的那样,建议/接受的解决方案不起作用。
我有一个在我的应用程序中使用的 Photo 类。一个帖子可以有一张照片。但是,我想重新使用多态关系来添加辅助照片。
前:
class Photo
belongs_to :attachable, :polymorphic => true
end
class Post
has_one :photo, :as => :attachable, :dependent => :destroy
end
期望:
class Photo
belongs_to :attachable, :polymorphic => true
end
class Post
has_one :photo, :as => :attachable, :dependent => :destroy
has_one :secondary_photo, :as => :attachable, :dependent => :destroy
end
但是,这失败了,因为它找不到类“SecondaryPhoto”。根据我从其他线程中可以看出的内容,我想做:
has_one :secondary_photo, :as => :attachable, :class_name => "Photo", :dependent => :destroy
除了调用 Post#secondary_photo 只会返回通过 Photo 关联附加的同一张照片,例如 Post#photo === Post#secondary_photo。查看 SQL,它确实 WHERE type = "Photo" 而不是我想要的 "SecondaryPhoto" ......
想法?谢谢!