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:"">

1 comment:

mary Brown said...

IEEE Final Year projects Project Center in Chennai are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation. For experts, it's an alternate ball game through and through. Smaller than expected IEEE Final Year project centers ground for all fragments of CSE & IT engineers hoping to assemble. Final Year Project Domains for IT It gives you tips and rules that is progressively critical to consider while choosing any final year project point.

JavaScript Training in Chennai

JavaScript Training in Chennai

The Angular Training covers a wide range of topics including Components, project projects for cseAngular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training