Updating an attribute after creating a callback updates the entire record

In my Rails application, I am trying to update a model attribute using update_attribute in the after_create . I can successfully update the attribute, but for some reason, all the other model attributes are also updated when I do this. Thus, although the model name attribute (for example) has not changed, it is set (the current value to it) in the database update request.

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

+4
source share
1 answer

Yes, I believe this is consistent behavior because this instance of the model you just created was not reloaded. Therefore, the β€œchanged” attributes were not reset.

Sorry if this is not a very clear explanation. To demonstrate, run the debugger in the after_create method. For instance.

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

Then, when the debugger starts:

 p self.changed 

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

One way 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 that you change will be updated in the SQL query.

Hope that makes sense :-)

+4
source

All Articles