诗歌rails 之named_scope的用法

Nick Kallen颇受欢迎的has_finder插件以named_scope的方式集成到了Rails 2.x版本,例子:

Ruby代码
  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
  6. # Standard usage
  7. User.active # same as User.find(:all, :conditions => {:active => true})
  8. User.inactive # same as User.find(:all, :conditions => {:active => false})
  9. User.recent # same as User.find(:all, :conditions => ['created_at > ?', 1.week.ago])
  10. # They're nest-able too!
  11. User.active.recent
  12. # same as:
  13. # User.with_scope(:conditions => {:active => true}) do
  14. # User.find(:all, :conditions => ['created_at > ?', 1.week.ago])
  15. # end

has_finder中的好处同样可以在named_scope中找到 --- 你还能得到一些额外的好处。 User.all 默认作为 User.find(:all)的别名,可以之间使用。

高级

对某些需求,不要忘了has_finder的某些功能:

传递参数

给你命名的scope传递参数,便于在运行时指定条件。

Ruby代码
  1. class User < ActiveRecord::Base
  2. named_scope :registered, lambda { |time_ago| { :conditions => ['created_at > ?', time_ago] }
  3. end
  4. User.registered 7.days.ago # same as User.find(:all, :conditions => ['created_at > ?', 7.days.ago])

Named Scope Extensions

扩展命名的scope(和association_extensions有点类似)。

Ruby代码
  1. class User < ActiveRecord::Base
  2. named_scope :inactive, :conditions => {:active => false} do
  3. def activate
  4. each { |i| i.update_attribute(:active, true) }
  5. end
  6. end
  7. end
  8. # Re-activate all inactive users
  9. User.inactive.activate

匿名 scope

你还可以使用默认提供的scoped来构造。(词句不好翻译)

Ruby代码
  1. # Store named scopes
  2. active = User.scoped(:conditions => {:active => true})
  3. recent = User.scoped(:conditions => ['created_at > ?', 7.days.ago])
  4. # Which can be combined
  5. recent_active = recent.active
  6. # And operated upon
  7. recent_active.each { |u| ... }

(译者注:这和javascript中的匿名函数相似:var foo = function(x) { alert(x); };)

named_scope是很好的功能。如果你还没有开始用它,现在就开始。你将来会离不开它。还是要感谢一下Nick。

原文地址:http://ryandaigle.com/articles/2008/3/24/what-s-new-in-edge-rails-has-finder-functionality

如何把named_scope和paginate结合起来?

Ruby代码
  1. class Product < ActiveRecord::Base
  2. named_scope :online, :conditions => {:status => 1}, :include => [:variants, :catalogue_images, :categories]
  3. named_scope :from_category_ids, lambda { |cat_ids| {:conditions => "categories_products.category_id IN (#{cat_ids})", :include => :categories }}
  4. end
  5. class CatalogueController < RaidBase
  6. def category
  7. @products = Product.from_category_ids(@category.leaf_ids).online.paginate :page => params[:page], :per_page => params[:per_page]
  8. end
  9. end

参考网址:http://pastie.org/207771

posted @ 2009-10-11 16:58  麦飞  阅读(2019)  评论(0编辑  收藏  举报