Monday, December 28, 2009

Interesting Rails Methods: update_attribute

Method: update_attribute
Module: ActiveRecord::Base
Documentation: 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.

Notes:
This method actually does far more than just update an attribute. It updates the whole object without validations. This is fine if you just retrieved the object from the database but it can be a disaster if you have modified other attributes on the object.

Given:

Article.find(1)
#<Article id:1 title:"title" body:"first article">

Safe usage of update attribute:

article = Article.find(1)
article.update_attribute(:title, "new title")
Article.find(1)
#<Article id:1 title:"new title" body:"first article">

Unsafe usage of update attribute:

article = Article.find(1)
article.body = ""
article.update_attribute(:title, "new title")
Article.find(1)
#<Article id:1 title:"new title" body:"">