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

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
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)