我有同样的问题:Rails Polymorphic Association with multiple associations on the same model
但这个问题的解决方案对我不起作用。我有一个图片模型和一个事件模型。活动有许多图片和一张封面图片。这两位都是模特。
class Picture < ActiveRecord::Base
belongs_to :image, polymorphic: true
end
class Event < ActiveRecord::Base
has_many :pictures, as: :image, :dependent => :destroy
has_one :cover_picture, -> { where image_type: "CoverPicture"},
class_name: Picture, foreign_key: :image_id,
foreign_type: :image_type, dependent: :destroy
end这里的问题是,当我创建一个新图片并将其设置为事件的cover_picture时,它不会将image_type设置为"CoverPicture“。在将image_type设置为"CoverPicture“之后,当我尝试保存它时,它会错误地使用"NameError: uninitialized CoverPicture”
发布于 2016-11-29 18:35:40
image_type在这种多态关联中具有特定的功能.它标识关联的模型(就像image_id标识id一样)。
您不应该更改image_type,因为这会破坏关联。
在图片模型中创建一个新的布尔列,比如cover_picture,您可以.
has_one :cover_picture, -> {where cover_picture: true} ...这的优点是您的封面图片也包括在您的图片协会,但如果您希望该图片排除在has_many之外,那么您也可以应用where子句。
has_many :pictures, -> {where.not cover_picture: true} ...https://stackoverflow.com/questions/40873056
复制相似问题