Aug 20, 2008 @ 12:46 pm

I used to be a fan of the has_finder gem written by Nick Kallen.

Now with Rails 2.1, this functionnality is built-in so you don’t need to install the gem.

The named_scope method allows you to add finders to any model. A code snippet is worth 10000 words :

  1. class Story < ActiveRecord::Base
  2.   named_scope :hilarious, :conditions => ["type = ?","comedy"]
  3.   named_scope :popular, :conditions => ["popularity_level > ?", 3]
  4. end

Doing this you can chain expressions like this :

  1. funny_stories = @all_stories.hilarious
  2. funny_and_popular = @all_stories.hilarious.popular

Maybe you knew it, maybe you didn’t. If you didn’t, now you know it. (I feel very smart about this last sentence. I think I am going to put this in my room somewhere)

Bookmark this post : These icons link to social bookmarking sites where readers can share and discover new web pages.
  • DZone
  • Reddit
  • del.icio.us
  • Digg
  • Furl
  • Technorati
  • StumbleUpon
Rate this post :
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...
Posted under : short & sweet
2 Comments
MyAvatars 0.2

Minor nitpick: named_scope was introduced in Railes 2.1, so anyone using Rails 2.0.2 (like me) still has to use has_finder.

Comment by : pete
— August 20, 2008 @ 2:42 pm

MyAvatars 0.2

Thanks for the precision Pete. I’m going to update the original post.

Comment by : Frank
— August 20, 2008 @ 3:10 pm




Leave a comment
Name (required)
Email (will not be publish) (required)
Website