Translate

April 17, 2012

What is different in update_all, update, update_attribute, update_attributes methods of Active Record

We use Active Record update* methods regularly, following text explains the difference between all update* the methods

update(id,attributes)
Update single or multiple objects using update method of active record. When update method is called it invokes model based validation, and save the object when validation passes successfully else object is not save.
It accepts two arguments, id and attributes which need to update.
User.update(1,:first_name => "John",:last_name => "Turner")
same way you are able to update multiple objects.
User.update([1,2],[{:first_name => "John",:last_name => "Turner"},{:department => "admin"}])

update_all(attribute, conditions, options)
It updates the given attribute of object by invoking specified conditions and options like order, limit. This will not invoke validation rules, methods of the model.
User.update_all("department = admin, "user_role Like '%admin'",:limit => 10)

update_attribute
This method update a single attribute of object without invoking model based validation.
user = User.find_by_id(params[:id])
user.update_attribute :role,"admin_manager"

update_attributes
This method update multiple attribute of single object and also pass model based validation.
attributes = {:first_name => "Peter", :age => 30}
user = User.find_by_id(params[:id])
user.update_attributes(attributes)

I think this article helped you to understand different Active Record update* methods. And which method to use in specific situation.
If have any query or suggestion than simply leave the comment.

Related posts:
Difference between update_attribute and update_column 
What is different in update_all, update,  update_attribute, update_attributes methods of Active Record
Difference between .nil?, .empty?, .blank?, .present? 
render vs redirect_to in Ruby on Rails

About
Post a Comment