Search code examples
ruby-on-railsrubypolymorphic-associationscocoon-gem

Validation Failed using Cocoon for Polymorphic Association


I have the following models in my schema:

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

Whenever I try to save a notification now - I get the an error - Validation failed: Impacts impactable must exist

I've tried to create impacts from notifications manually with Notification.last.impacts.create and they work fine.

What could be the problem here?

More info - When I add a byebug to the @notification object before it saves in the controller - this is the output -

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

And also checking for it's associations --

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

Solution

  • You just need to add inverse_of: :impactable to your Notifications Model.

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