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.
Posted by Emanuel to makandra dev (2017-09-07 10:28)