【问题标题】:Multiple polymorphic associations work with rails 4 not rails 5多个多态关联适用于 rails 4 而不是 rails 5
【发布时间】:2017-07-31 01:25:42
【问题描述】:

以下代码在 rails 4.2.7 上运行良好,但在 rails 5+ 上它会抛出 NameError initialized constant 'BonesReqPhoto'

模型 l2_requirement.rb

has_one :bones_req_photo, -> { where requireable_type: "BonesReqPhoto" }, 
  class_name: "ReqPhoto", foreign_key: :requireable_id, 
  foreign_type: :requireable_type
has_one :bubbling_req_photo, -> { where requireable_type: "BubblingReqPhoto" }, 
  class_name: "ReqPhoto", foreign_key: :requireable_id, 
  foreign_type: :requireable_type

模型 req_photo.rb

belongs_to :requireable, polymorphic: true

模型多次使用多态关联。 where 约束用于区分两者。

我使用这个答案来弄清楚如何为 rails 4 解决这个问题,但试图让它适用于 rails 5 却无济于事:imageable type is not setting for polymorphic associations

在 Rails 5 中执行此操作的正确方法是什么?

【问题讨论】:

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


    【解决方案1】:

    原来我误解了原始指南。我试图替换requireable_type,这导致后来很头疼。

    正确答案是添加新列。我选择了req_type

    has_one :bones_req_photo, -> { where req_type: "BonesReqPhoto" }, 
      class_name: "ReqPhoto", as: :requireable
    has_one :bubbling_req_photo, -> { where req_type: "BubblingReqPhoto" }, 
      class_name: "ReqPhoto", as: :requireable 
    

    【讨论】:

      猜你喜欢
      • 2016-04-05
      • 1970-01-01
      • 2013-11-28
      • 1970-01-01
      • 2021-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多