【问题标题】:Validation Failed using Cocoon for Polymorphic Association使用 Cocoon 进行多态关联验证失败
【发布时间】:2016-08-22 04:25:58
【问题描述】:

我的架构中有以下模型:

class Notification < ApplicationRecord
  has_many :impacts, as: :impactable
  accepts_nested_attributes_for :impacts, reject_if: :all_blank, allow_destroy: true
end

class Impact < ApplicationRecord
  #association
  belongs_to :impactable, polymorphic: true

  #enum
  enum impact_type: [:full_school, :standard, :section]
end

每当我现在尝试保存通知时 - 我都会收到错误消息 - Validation failed: Impacts impactable must exist

我尝试使用 Notification.last.impacts.create 手动从通知中创建影响,并且它们工作正常。

这可能是什么问题?

更多信息 - 当我在 @notification 对象保存到控制器之前添加一个 byebug 时 - 这是输出 -

>> @notification
=> #<Notification id: nil, notification_type: "email", title: "Test", content: "Tomorrow is a holiday", created_at: nil, updated_at: nil>

并且还检查它的关联 --

>> @notification.impacts
=> #<ActiveRecord::Associations::CollectionProxy [#<Impact id: nil, impact_type: "standard", standard: 2, created_at: nil, updated_at: nil, impactable_id: nil, impactable_type: "Notification", section: "">]>

【问题讨论】:

    标签: ruby-on-rails ruby polymorphic-associations cocoon-gem


    【解决方案1】:

    您只需将inverse_of: :impactable 添加到您的通知模型。

    has_many :impacts, as: :impactable, inverse_of: :impactable
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-30
      • 1970-01-01
      • 1970-01-01
      • 2011-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多