Wednesday, 20 June 2012

difference between update_attribute and update_attributes

Hi,

update_attribute and update_attributes both are used to update the object without having explicitly Active Record to update.

The main difference between them is update_attribute will not call validations and callbacks, it will skip validations and callbacks while updating the record.

Let me explain clearly

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


In the above parameter that was passing for the save is false. i.e  save(perform_validation = false)). So it will skip the validations and there by callbacks.


Coming to update_attributes

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

In the above case we are not passing any parameter for the save. So it will be default 'true'. So it will call the validations.

Important point at here is, we should choose update_attribute mainly for updating Boolean column datatypes, where it is not required that much validations.

Here is the syntax that should be used for update_attribute

@user.update_attribute(:status, true)

The main goal of update_attribute is to bypass the stuff and make the update operation fast.




Thank You,
Uma Mahesh.

No comments:

Post a Comment