Reputation: 460
Case1: Creating a new record for a model with assigning the associated object(Status object instead of Status.id) like
visit = Visit.create(:date => Date.today, :status => Status.first)
visit.status_id #=> 1
After creating the record
I'm trying to update the attribute 'status_id' (Status.id instead of Status object) but it returns the old value even calling reload after save the object. Example:
visit.status_id = Status.last.id
visit.save
visit.reload
visit.status_id #=> 1
When I calling reload method after create it is working as expected
visit = Visit.create(:date => Date.today, :status => Status.first)
visit.status_id #=> 1
visit.reload
visit.status_id = 2
visit.save
visit.status_id #=> 2
Case2: If I assigning the 'status_id' value instead of Status object, then no need to reload object and its working fine
visit = Visit.create(:date => Date.today, :status_id => Status.first.id)
visit.status_id #=> 1
visit.status_id = 2
visit.save
visit.status_id #=> 2
Using the two cases above, when should I use the reload
method? Should it be before or after save
?
Upvotes: 2
Views: 13558
Reputation: 2228
I think your understanding of how save
and reload
work is basically correct. Your results certainly seem to be inconsistent. I have a feeling based on your results that your save
is failing.
save
will try to store the local version to the database. It does not refresh any values from the database if the model has changed since you loaded it. If the save
fails, the local values are still whatever you set them to, but the database will have the old values.
reload
overwrites any local changes you have made and sets them to the database values.
Assuming there is no contention on the database for the models you are concerned with, let's walk through your examples.
Example 1
If the save
works, then the reload
will not do anything and the value of visit.status_id
will be Status.last.id
. However, if the save
fails then the value of visit.status_id
will be whatever it was in the database originally.
Example 2
If the create
does not work then the reload
would give a RecordNotFound
error because you can't reload
something that hasn't been persisted. After that you set the status_id
to 2 and then call save
. Whether the save
succeeds or fails, the local value of status_id
will remain as 2. However, the database value depends on whether it passed or failed.
Example 3 Hey! This is the same as example 2 except for the reload.
Here is some documentation, but I'm not sure how helpful you will find it: http://apidock.com/rails/ActiveRecord/Persistence/save
http://apidock.com/rails/ActiveRecord/Persistence/reload
You might want to check for save
success or call save!
to ensure the save
is actually working.
I hope that helps.
Upvotes: 5