Rails: #update_attribute vs #update_attributes

obj.update_attribute(:only_one_field, 'Some Value')
obj.update_attributes(field1: 'value', field2: 'value2', field3: 'value3')

Both of these will update an object without having to explicitly tell ActiveRecord to update.

Rails API says:

update_attribute

Updates a single attribute and saves the record without going through the normal validation procedure. This is especially useful for boolean flags on existing records. The regular update_attribute method in Base is replaced with this when the validations module is mixed in, which it is by default.

update_attributes

Updates all the attributes from the passed-in Hash and saves the record. If the object is invalid, the saving will fail and false will be returned.

So if I don’t want to have the object validated I should use #update_attribute. What if I have this update on a #before_save, will it stackoverflow?

My question is does #update_attribute also bypass the before save or just the validation.

Also, what is the correct syntax to pass a hash to #update_attributes … check out my example at the top.

11 Answers
11

Leave a Comment