Skip to content

Conversation

@RohanM
Copy link
Contributor

@RohanM RohanM commented Aug 13, 2025

When an ActiveRecord model uses accepts_nested_attributes_for, AR will enable autosave so that saving the parent model will also save changes to the child / children. Autosave will check for changes using the changed_for_autosave? method (eg. belongs_to, has_one, has_many). At present, ActiveType doesn't override this method, so this check is oblivious to virtual attribute changes:

class Child < ActiveRecord::Base
  belongs_to :record
  accepts_nested_attributes_for :record
end

class Record < ActiveRecord::Base
end

class FormChild < ActiveType::Record[Child]
  change_association :record, class_name: 'FormRecord'
end

class FormRecord < ActiveType::Record[Record]
  attribute :virtual_string, :string
end

record = FormRecord.create!
child = Child.create!(record: record)

form_child = FormChild.new(record: record)
form_child.record_attributes = {
  'id' => record.id,
  'virtual_string' => 'record virtual'
}

# We expect this to result in record receiving `save`, but it doesn't
form_child.save!

Implement changed_for_autosave? to fix this issue.

@RohanM RohanM force-pushed the autosave-virtual-attribute-changes branch from 3660666 to e618751 Compare August 13, 2025 00:10
@RohanM RohanM changed the title Autosave has_one virtual attribute changes Autosave virtual attribute changes Aug 13, 2025
@kratob kratob merged commit 66d9153 into makandra:main Aug 13, 2025
9 checks passed
@kratob
Copy link
Member

kratob commented Aug 13, 2025

Thanks for the PR!
Released the change as version 2.6.3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants