Association to polymorphic model does not determine inverse_of automatically

Updated . Posted . Visible to the public.

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

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.

Last edit
Felix Eschey
License
Source code in this card is licensed under the MIT License.
Posted by Emanuel to makandra dev (2017-09-07 10:28)