ActiveType #change_association: Define { autosave: true } on parent models

Posted . Visible to the public.

Consider the following models and form models:

class Parent < ApplicationRecord
  has_many :children, class_name: 'Child', foreign_key: 'parent_id'
end

class Parent::AsForm < ActiveType::Record[Parent]
  change_association :children, class_name: 'Child::AsForm', foreign_key: 'parent_id', autosave: true, inverse_of: :parent

  accepts_nested_attributes_for :children
  validates_associated :children
end
class Child < ApplicationRecord
  belongs_to :parent, inverse_of: :children
end

class Child::AsForm < ActiveType::Record[Child]
  change_association :parent, class_name: 'Parent::AsForm', inverse_of: :children
end

When saving a Parent::AsForm record with nested Child::AsForm records, the children will not be saved.
This behavior also applies to the case where you override the association with has_many :children, ... and belongs_to :parent, ....

Solution

This can be fixed with appending autosave: true to the Parent model:

class Parent < ApplicationRecord
  has_many :children, class_name: 'Child', foreign_key: 'parent_id', dependent: :destroy, autosave: true
end

Then saving children of Parent::AsForm's will work as expected.

Jakob Scholz
Last edit
Jakob Scholz
License
Source code in this card is licensed under the MIT License.
Posted by Jakob Scholz to makandra dev (2021-01-29 08:03)