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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)