Michael Victor Michael Victor - 1 year ago 104
Ruby Question

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

class Impact < ApplicationRecord
belongs_to :impactable, polymorphic: true

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

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

Answer Source

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

has_many :impacts, as: :impactable, inverse_of: :impactable
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download