I'm a Ruby on Rails and React Native enthusiast with over four years of experience creating innovative software solutions. I work well in teams and am always up for challenging projects. I enjoy playing chess and gaming in my free time.
1 minute read
ActiveRecord
AutosaveAssociation
is a module that takes care of automatically saving associated records when their parent is saved.
In addition to saving, it also destroys any associated records that were marked for destruction.
Association with autosave option defines several callbacks on your model
(around_save, before_save, after_create, after_update).
When saving a record, autosave adds callbacks to save its associations.
Since the associations can have similar callbacks for the inverse,
endless loops could occur.
To prevent these endless loops, the callbacks for has_many and belongs_to
are made non-cyclic (methods that only execute once).
This is implemented in the Ruby define_non_cyclic_method method and
the same wasn’t used for the has_one callbacks.
Before
While has_one association callbacks didn’t result in endless loops,
they could execute multiple times.
For a bidirectional has_one with autosave enabled,
the save_has_one_association gets called twice creating inconsistency.
After
Starting with Rails 7, these
changes
are added for the has_one autosave callbacks to be non-cyclic.
By doing this the autosave callbacks are made more consistent for all 3 cases: has_many,
has_one and belongs_to.
How Rails fixed it?
In the previous versions of Rails, the callbacks were defined as follows:
The Rails team added define_non_cyclic_method under reflection.has_one? condition.