This post originated from an RSS feed registered with Ruby Buzz
by rwdaigle.
Original Post: What's New in Edge Rails: Touching
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.
There are often times when you want an update made to one object to be reflected up the object graph as an update of an associated parent object. For instance, if a new comment is created on an article, you may very well want to mark the article as being updated. With the new touch feature of ActiveRecord, this is a whole lot easier. Using our previous example, here’s is how it works:
12345678910111213141516171819
classArticle < ActiveRecord::Base has_many :commentsendclassComment < ActiveRecord::Base# Make create/update/deletes of a comment mark its# parent article as updated belongs_to :article, :touch => trueend# Adding a new comment marks the article as being updatedarticle.updated_at #=> "Mon Apr 20 07:42:53 -0400 2009"article.comments.create(:body => "New comment")article.updated_at #=> "Mon Apr 20 07:43:27 -0400 2009"# Same for updates/deletesarticle.comments.first.destroyarticle.updated_at #=> "Mon Apr 20 07:45:23 -0400 2009"
This is a great way to keep tightly coupled domain models in-sync without resorting to a potential maze of callback logic.
Also, if you have a timestamp field named something other than the standard updated_at or updated_on you can explicitly specify that field as the value to the :touch option and it will get marked instead:
12345678910111213
classArticle < ActiveRecord::Base has_many :comments validates_presence_of :last_updated_at# non-standardendclassComment < ActiveRecord::Base belongs_to :article, :touch => :last_updated_atend# Adding a new comment marks the article as being updatedarticle.last_updated_at #=> "Mon Apr 20 07:42:53 -0400 2009"article.comments.create(:body => "New comment")article.last_updated_at #=> "Mon Apr 20 07:43:27 -0400 2009"
Also, somewhat conveniently, you can invoke touch directly on a model to update its timestamp outside any association callbacks: