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?
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 :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With