Translate

April 18, 2012

Difference between update_attribute and update_column


We use update_attribute most of the time, update_column serves same purpose, there is below difference
  • update_attribute
  • It updates the single attribute with bypassing the validations.
  • update_column
  • It updates the single attribute with bypassing the validations as well as the callbacks.

Syntax of both are as follow:
Model.update_attribute :field, 'value'
Model.update_column :field, 'value'

update_column is added in the rails 3.2.1

In case if you need to use update_column in lower Rails version then you can apply simple patch given below.

module ActiveRecord
  module AttributeMethods
    def update_column(name, value)
      name = name.to_s
      self.class.update_all({ name => value }, self.class.primary_key => id) == 1
     end
   end
end

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

No comments: