使用 Cocoon 进行多态关联验证失败

Validation Failed using Cocoon for Polymorphic Association

我的架构中有以下模型:

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: "">]>

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

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