This post originated from an RSS feed registered with Ruby Buzz
by rwdaigle.
Original Post: What's New in Edge Rails: Default Scoping
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.
It’s pretty common to want SQL queries against a particular table to always be sorted the same way, and is one of the reasons why I added the ordered scope to the utility scopes gem. For instance, when dealing with collections of articles it is reasonable to expect that the default ordering be most recent first, i.e. created_at DESC. Well now you can specify default ordering, and other scopes, in edge rails directly in your ActiveRecord model.
Taking our Article example let’s specify the aforementioned default ordering:
Now, when any find method or named_scope is executed the default ordering comes along for the ride:
Article.find(:all) #=> "SELECT * FROM `articles` ORDER BY created_at DESC"
The same holds true for any named scopes you might have:
123456
classArticle < ActiveRecord::Base default_scope :order => 'created_at DESC' named_scope :published, :conditions => { :published => true }endArticle.published #=> "SELECT * FROM `articles` WHERE published = true ORDER BY created_at DESC"
There are some things to keep in mind, however. First is that scopes like :joint, :offset, :limit and :order will get clobbered by the innermost rule. For example, here the default scope ordering loses out to the named_scope ordering.
123456789
classArticle < ActiveRecord::Base default_scope :order => 'created_at DESC' named_scope :published, :conditions => { :published => true },:order => 'published_at DESC'end# published_at DESC clobbers default scopeArticle.published#=> "SELECT * FROM `articles` WHERE published = true ORDER BY published_at DESC"
Also keep in mind that the default scoping is inherited, so child-classes of Article will have the same default scoping.
default_scope is a great way to specify reasonable query defaults and relieve yourself of having to create your own named_scopes for that purpose or specify such conditions at every invocation. Yes, I just said ‘relieve yourself’... giggity giggity