This post originated from an RSS feed registered with Ruby Buzz
by rwdaigle.
Original Post: What's New in Edge Rails: Dynamic Scope Methods
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.
For quite some time now you’ve been able to perform simple queries using dynamic find_all_by_xx_and_yy methods:
12
Article.find_by_published_and_user_id(true, 1)#=> "SELECT * FROM articles WHERE published = 1 AND user_id = 1"
These dynamic finders provide an easy way to quickly encapsulate non-reused query conditions (for commonly used query logic you should consider using named scopes). The downside, however, is that you can’t chain query conditions when using these dynamic finders.
With the recent addition of dynamic scopes, however, you now have a way to both quickly specify query logic and chain further conditions. The naming works in the same manner as dynamic finders and the chaining works in the same fashion as conventional named scopes:
12
Article.scoped_by_published_and_user_id(true, 1).find(:all, :limit => 5)#=> "SELECT * FROM articles WHERE published = 1 AND user_id = 1 LIMIT 5"
Note how you can hang further chainable query methods off the dynamic scope here? You could also have preceded the dynamic scope with another scope, or even another dynamic scope:
12
Article.scoped_by_published(true).scoped_by_user_id(1)#=> "SELECT * FROM articles WHERE published = 1 AND user_id = 1"
This is really just another tool to put in your toolbox based on the powerful named_scope functionality of ActiveRecord.