3 Comments
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)
3 CommentsMinor nitpick: named_scope was introduced in Railes 2.1, so anyone using Rails 2.0.2 (like me) still has to use has_finder.
Thanks for the precision Pete. I’m going to update the original post.
[...] 在rubyfleebie上看到这篇文章,里面有个不错的技巧,在Rails 2.1中添加了named_scope特性,看下面这个例子: Ruby代码 [...]

