update_attribute, update_attributes and update_column (Ruby on Rails)
update_attribute
Updates a single attribute and saves the record without going through the normal validation procedure. This is especially useful for boolean flags on existing records. The regular update_attribute method in Base is replaced with this when the validations module is mixed in, which it is by default.
Also note that
- Validation is skipped.
- Callbacks are invoked.
- updated_at/updated_on column is updated if that column is available.
- Updates all the attributes that are dirty in this object.
update_attributes
Updates all the attributes from the passed-in Hash and saves the record. If the object is invalid, the saving will fail and false will be returned.
Examples:
Object.update_attribute(:only_one_field, "Some Value")
Object.update_attributes(:field1 => "value", :field2 => "value2", :field3 => "value3")
Object.update_attributes(params[:user])All of these will update an object in a database without having to explicitly tell AR to update.
update_attribute can update only one column with this and updated_at is not updated.
Validation
Use update_attribute to skip callbacks and validations.
The difference between two is update_attribute use save(false) where as update_attributes uses save or you can say save(true).
Callbacks
If perform_validation is false while calling save then it skips validation, and it also means that all the before_* callbacks associated with save.
Update attributes without saving
update_column(name, value)
Updates a single attribute of an object, without calling save.
- Validation is skipped.
- Callbacks are skipped.
- updated_at/updated_on column is not updated if that column is available.
Raises an ActiveRecordError when called on new objects, or when the name attribute is marked as readonly.
.attributes property
Use .attributes to update attributes of the model without saving it to a database.
@car = Car.new(:some_field=>'value', :another_field=>'value')
#
@car.attributes = {:title => 'Toyota', :year => 2005, :used=>false}
#other processing
..
#finally, save to DB
@car.save
Ref.
Discussions on StackOverflow:
http://stackoverflow.com/questions/2778522/rails-update-attribute-vs-update-attributes
Comments
-
http://twitter.com/Elentras Jérémy Mortelette



