Rails: update_attribute vs update_attributes

update_attribute

This method update single attribute of object without invoking model based validation.

obj = Model.find_by_id(params[:id])
obj.update_attribute :language, “java”

update_attributes

This method update multiple attribute of single object and also pass model based validation.

attributes = {:name => “BalaChandar”, :age => 23}
obj = Model.find_by_id(params[:id])
obj.update_attributes(attributes)

Hope this answer will clear out when to use what method of active record.


Please refer to update_attribute. On clicking show source you will get following code

      # File vendor/rails/activerecord/lib/active_record/base.rb, line 2614
2614:       def update_attribute(name, value)
2615:         send(name.to_s + '=', value)
2616:         save(false)
2617:       end

and now refer update_attributes and look at its code you get

      # File vendor/rails/activerecord/lib/active_record/base.rb, line 2621
2621:       def update_attributes(attributes)
2622:         self.attributes = attributes
2623:         save
2624:       end

the difference between two is update_attribute uses save(false) whereas update_attributes uses save or you can say save(true).

Sorry for the long description but what I want to say is important. save(perform_validation = true), if perform_validation is false it bypasses (skips will be the proper word) all the validations associated with save.

For second question

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

Your example is correct.

Object.update_attributes(:field1 => "value", :field2 => "value2", :field3 => "value3")

or

Object.update_attributes :field1 => "value", :field2 => "value2", :field3 => "value3"

or if you get all fields data & name in a hash say params[:user] here use just

Object.update_attributes(params[:user])

Tip: update_attribute is being deprecated in Rails 4 via Commit a7f4b0a1. It removes update_attribute in favor of update_column.


Also worth noting is that with update_attribute, the desired attribute to be updated doesn't need to be white listed with attr_accessible to update it as opposed to the mass assignment method update_attributes which will only update attr_accessible specified attributes.