Difference between update_attribute, update_attributes and update_column in ruby on rails

update_attribute: This is used when need to update an attribute with validations(false) & save(false).

  • validations skipped.
  • callbacks are invoked
  • updated_at default rails column gets updated
  • all dirty attributes get updated.

ex: Object.update_attribute(:field, “value”)

update_attributes: This can be used to update many attributes of an object together  or an hash with validations(true) & save(true). If object is not correct it will fail.

  • validations are invoked.
  • callbacks are invoked
  • updated_at default rails column gets updated

ex: Object.update_attribute(:field, “value”)
Object.update_attributes(:field1 =>”value1″, :field2 => “values”)
Object.update_attributes(params[:model])

update_column:  This is used when need to update an attribute with validations(false) & save(false). This works as update column query in sql without calling save.

  • validations are skipped.
  • callbacks are skipped
  • updated_at default rails column DO NOT get updated.

 

Similarly update_columns(:field => value) can be used to update multiple columns without save.

.attributes property: use this on model to update attributes without saving to database.

ex:  @user= User.new(:first_name = ‘name’, :last_name=>’surname’)

@user.attributes = (:first_name = ‘Aakash’, :last_name=>’Sharma’)

@user.save