Give little names to your pet SQL queries with Rails 2.1

I don't know about you but every time some news come out about Ruby on Rails, I'm saying to myself: "there is no way this can be any better that it already is". And every time, they manage to find a way to impress me.
This time around, Ryan Daigle talks about the new named_scope feature in his "What's New in Edge Rails: Has Finder Functionality" article.

This basically let you define methods to your ActiveRecord objects which will simplify future queries. For those of you who haven't caught on the Rails train yet, just imagine an ActiveRecord object as an abstraction to a database table, getting all the tables' fields as properties and providing easy SQL requests. And that's a given for a long time in the Rails community.

Now, what named_scope adds is a way to define queries as methods. Let's see Ryan's sample to see how powerful this is:

  1. class User < ActiveRecord::Base
  2. named_scope :active, :conditions => {:active => true}
  3. named_scope :inactive, :conditions => {:active => false}
  4. named_scope :recent, lambda { { :conditions => ['created_at > ?', 1.week.ago] } }
  5. end
  7. # Standard usage
  8. # same as User.find(:all, :conditions => {:active => true})
  9. User.inactive # same as User.find(:all, :conditions => {:active => false})
  10. User.recent # same as User.find(:all, :conditions => ['created_at > ?', 1.week.ago])
  12. # They're nest-able too!

Isn't that a great way to make simple or more complex queries ? Some of the advantages I see are:

  • Better code readability and maintainability: the queries are separated from the code
  • Security as you can rapidly check out all your models for investigation of potential harmful queries
  • Simplicity: you've got to love the syntax "" to request for the most recent active users !

Even though once again I don't imagine something better can come out from Rails' master minds, I'll be careful enough and keep this thought to myself !

Average: 2.5 (4 votes)