This post originated from an RSS feed registered with Ruby Buzz
by rwdaigle.
Original Post: What's New in Edge Rails: Dirty Objects
Feed Title: Ryan's Scraps
Feed URL: http://feeds.feedburner.com/RyansScraps
Feed Description: Ryan Daigle's various technically inclined rants along w/ the "What's new in Edge Rails" series.
The ability to track whether or not your active record objects have been modified or not becomes a lot easier with the new dirty object functionality of edge rails. It’s dead simple, and pretty slick, to use:
1234567891011121314
article = Article.find(:first)article.changed? #=> false# Track changes to individual attributes with# attr_name_changed? accessorarticle.title #=> "Title"article.title = "New Title"article.title_changed? #=> true# Access previous value with attr_name_was accessorarticle.title_was #=> "Title"# See both previous and current value with attr_name_change accessorarticle.title_change #=> ["Title", "New Title"]
Beyond the clever attribute based accessor methods, you can also query to object directly for its list of all changed attributes. (Continuing from the previous example):
12345
# Get a list of changed attributesarticle.changed #=> ['title']# Get the hash of changed attributes and their previous and current valuesarticle.changes #=> { 'title' => ["Title", "New Title"] }
Note: Once you save a dirty object it clears out its changed state tracking and is once again considered unchanged.
If you’re going to be modifying an attribute outside of the attr= writer, you can use attr_name_will_change! to tell the object to be aware of the change:
And coming down the pipe is a feature that will make the most of this functionality – partial SQL updates that will only update attributes that have changed…