Use named_scope to add elegant finders to your models

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 :

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

Doing this you can chain expressions like this :

funny_stories = @all_stories.hilarious
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)

14 thoughts on “Use named_scope to add elegant finders to your models

  1. I was suggested this website by my cousin. I’m not sure
    whether this post is written by him as nobody else know such
    detailed about my difficulty. You are amazing! Thanks!

  2. I was wondering if you ever thought of changing
    the structure of your site? Its very well written; I love what
    youve got to say. But maybe you could a little more in the way
    of content so people could connect with it better. Youve got an awful lot of text for only having 1 or
    2 images. Maybe you could space it out better?

  3. Superb site you have here but I was wondering if you
    knew of any discussion boards that cover the same topics discussed here?
    I’d really love to be a part of group where I can get suggestions from
    other experienced people that share the same interest.
    If you have any recommendations, please let me know.
    Bless you!

  4. After I initially left a comment I appear to have clicked the
    -Notify me when new comments are added- checkbox and now each time
    a comment is added I receive four emails with the same comment.
    Is there a means you are able to remove me from that service?
    Many thanks!

  5. It’s a shame you don’t have a donate button! I’d definitely donate
    to this outstanding blog! I suppose for now i’ll settle for book-marking and adding your RSS feed to my Google account.
    I look forward to brand new updates and will share this
    blog with my Facebook group. Talk soon!

Leave a Reply

Your email address will not be published. Required fields are marked *