【问题标题】:Rails Polymorphic Association with multiple associations on the same model bugRails 多态关联与同一模型上的多个关联错误
【发布时间】:2016-11-29 18:23:11
【问题描述】:

我有同样的问题: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

这里的问题是,当我创建新图片并将其设置为事件的封面图片时,它不会将 image_type 设置为“封面图片”。当我在将 image_type 专门设置为“CoverPicture”后尝试保存它时,它会出现“NameError:未初始化的常量 CoverPicture”的错误

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 ruby-on-rails-4.2


    【解决方案1】:

    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} ...
    

    【讨论】:

    • link 上的所有答案都表明了我的尝试。有什么想法为什么它可能对他们有用?
    • 该链接上评分最高的答案正是我的答案。他建议使用一个名为photo_type 的额外的不同字段(我建议使用一个名为cover_picture 的不同字段)。他没有使用(在他的情况下)是attachable_typeattachable_id的多态字段,所以他的photo_type字段是一个单独的列,不会弄乱他的多态关联。如果您想创建一个名为photo_type 的新字段,那很好,请继续。但不要使用image_type,因为您的多态字段是image_typeimage_id
    猜你喜欢
    • 2011-01-30
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 2011-05-06
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    相关资源
    最近更新 更多