Read more

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

Jakob Scholz
January 29, 2021Software engineer at makandra GmbH

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

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.

Posted by Jakob Scholz to makandra dev (2021-01-29 09:03)