Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Simple ActiveRecord Updates in Rails

I'm just diving into ActiveRecord and have not been able to find an answer to my question. If I am updating an object's attributes and then calling save()... will ActiveRecord save to the DB ONLY when the new values are different from the old values?

Let's say I do something like this:

thing_to_update = Thing.find_or_create_by_code(some_code)
if thing_to_update.name != some_name 
    thing_to_update.update_attribute(:name, some_name)
end

I don't want to do extra calls to the db if I don't have to because I will potentially have to update a lot of objects. I tried to read through the docs and it doesn't mention anything about comparing new values with the old ones. Am I missing something here?

Thanks

like image 511
Ryan Ferretti Avatar asked Feb 02 '10 17:02

Ryan Ferretti


2 Answers

Active Record didn't used to do partial SQL updates, but it has since April 2008.

  • What's new in Edge Rails: Partial Updates
  • ActiveRecord::Dirty documentation
like image 111
John Topley Avatar answered Nov 13 '22 22:11

John Topley


ActiveRecord will not update your record if no attributes have changed. You can verify this yourself by calling thing_to_update.save from the console and observing the log. ActiveRecord will load the record, but it will not attempt to update it.

like image 37
Logan Koester Avatar answered Nov 13 '22 22:11

Logan Koester