Difference between active record methods – update, update_all, update_attribute, update_attributes

1. update(id,attributes)

Update single or multiple objects using update method of active record. When update method invokes it invoke model based validation, save the object when validation passes  successfully else object is not save.

It requires two argument id and attributes which need to update.

Model.update(1,:language => “ruby”,:framework => “rails”)

same way you are able to update multiple objects.

Model.update([1,2],[{:language => “ruby”,:framework => “rails”},{:ide => “aptana”}])

2. update_all(attribute, conditions, options)

It updates the attribute of object by invoking specified conditions and options like order, limit. But disadvantage of this method is it’s not invoke validation of model.

Model.update_all(“language = “ruby”, “framework Like ‘%rails'”,:limit => 2)

3. 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, “php”

4. update_attributes

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

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

Hope this article will clear out when to use what method of active record. If have any query or suggestion than simply leave the comment.

2 thoughts on “Difference between active record methods – update, update_all, update_attribute, update_attributes

    • You are correct but update_attributes works on single object at a time. where Update used on multiple object as well.
      eg. Model.update([1,2],[{:language => “ruby”,:framework => “rails”},{:ide => “aptana”, :framework => “grails”}])

Leave a comment