views:

83

answers:

2

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

+4  A: 

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

John Topley
+2  A: 

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.

Logan Koester