Understanding ActiveRecord Autosave Association

ActiveRecord AutosaveAssociation is a module that is used for saving the child objects if the parent is saved and deleting the child objects if they are marked for destruction. This article will demonstrate how this works.

Assume that you have two models, User and Address. The relationship is defined as:

1
2
3
4
5
# app/models/user.rb

class User < ApplicationRecord
 has_one :address
end
1
2
3
4
5
# app/models/address.rb

class Address < ApplicationRecord
 belongs_to :user
end

Following is an example where child association will not be automatically saved because autosave association is not declared in the models:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
user = User.find(1)
user.name
=> "John"
user.address.address1
=> "797 Fulton Road" 

user.name = "Mike"
user.address.address1 = "897 Fulton Road"
user.save

user.reload.name
=> "Mike" 

user.address.reload.address1
=> "797 Fulton Road" 

Now declare autosave in the model.

1
2
3
4
5
# app/models/user.rb

class User < ApplicationRecord
 has_one :address, autosave: true
end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
user = User.find(1)
user.name
=> "Mike"
user.address.address1
=> "797 Fulton Road" 

user.name = "Stuart"
user.address.address1 = "897 Fulton Road"
user.save

user.reload.name
=> "Stuart" 

user.address.reload.address1
=> "897 Fulton Road" 

Now let’s talk about destruction.

1
2
3
4
5
6
7
8
9
10
user.address.mark_for_destruction
user.address.marked_for_destruction?
=> true 

user.address
=> #<Address id: 1, address1: "897 Fulton Road", address2: nil, city: "Clinton", state: "MD", zip: "20735", user_id: 1, created_at: "2020-05-03 13:02:25", updated_at: "2020-05-03 20:50:56"> 

user.save
user.reload.address
=> nil

There you have it!