Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating an attribute in an after create callback results in the entire record being updated

In my Rails application I'm trying to update a model's attribute using update_attribute in an after_create callback. I can successfully update the attribute, but for some reason all the model's other attributes are also updated when I do so. So, even though the model's name attribute (for example) has not changed it is set (to it's current value) in the database update query.

Is this the expected behaviour in Rails (2.3.8), or am I doing something wrong?

like image 950
Richard M Avatar asked Sep 01 '10 15:09

Richard M


1 Answers

Yes I believe this is consistent behaviour because that instance of your model that was just created has not been reloaded. Therefore the 'changed' attributes have not been reset.

Sorry if that's not a very clear explanation. To demonstrate, run the debugger in your after_create method. E.g.

def my_after_save_callback
  require 'ruby-debug'; debugger
  update_attribute(:foo, "bar")
end

Then when the debugger starts run:

p self.changed

An array of all the attributes that have been modified for this object will be returned. ActiveRecord will update all these attributes the next time the object is saved.

One way around this is to reload the object before updating the attribute.

def my_after_save_callback
  reload
  update_attribute(:foo, "bar")
end

This will reset the 'changed' attributes and only the specific attribute you modify will be updated in the SQL query.

Hope that makes sense :-)

like image 89
Sidane Avatar answered Sep 25 '22 02:09

Sidane