Read more

Association to polymorphic model does not determine inverse_of automatically

Emanuel
September 07, 2017Software engineer at makandra GmbH

You need to set the :inverse_of option manually for relations that have an association to a polymorphic model. Otherwise you will not be able to save a record with a nested polymorphic association.

class Event < ApplicationRecord
  has_many :letters, as: :record
end

class Letter < ApplicationRecord
  belongs_to :record, polymorphic: true
end

event = Event.new.letters.build
event.save! # => ActiveRecord::RecordInvalid: Validation failed: Record must exist
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

Using the :inverse_of option here will fix the problem.

class Event < ApplicationRecord
  has_many :letters, as: :record, inverse_of: :record
end

Note: It is not possible and necessary to set :inverse_of in the polymorphic model.

Posted by Emanuel to makandra dev (2017-09-07 12:28)