作者:Ryan Daigle 来源:JavaEye   酷勤网收集 2008-05-30

摘要
  广受欢迎的has_finder插件将会被加入到Rails 2.x版本中,以named_scope方式出现。你所喜欢的has_finder所有优点现在都被named_scope提供——还附带一些额外的优点。User.all成了User.find(:all)的另一种写法。

系列文章汇总《Ruby on Rails 2.1新特性

Nick Kallen的广受欢迎的has_finder插件将会被加入到Rails 2.x版本中,以named_scope方式出现。

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


你所喜欢的has_finder所有优点现在都被named_scope提供——还附带一些额外的优点。User.all成了User.find(:all)的另一种写法。


高级特性:

那些对discriminating有更多需求的,别忘了还有has_finder里的一些技巧。

传递参数

在运行时,将参数传递给named scope中的特定条件。


Ruby代码 复制代码

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


扩展Named Scope

扩展named scipes(一种类似集合扩展的风格)

Ruby代码 复制代码

  1. class User < ActiveRecord::Base   
  2.   named_scope :inactive:conditions => {:active => falsedo  
  3.     def activate   
  4.       each { |i| i.update_attribute(:activetrue) }   
  5.     end  
  6.   end  
  7. end  
  8.   
  9. # Re-activate all inactive users   
  10. User.inactive.activate  



匿名Scopes

你可以在第一个类使用scoped方法来传递scopes

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



name_scope是一个非常不错的功能,如果你还没开始使用它,请试着尝试下,你会发现再也离不开它了。万分感谢Nick

原文:ryandaigle.com
来自:http://www.javaeye.com/news/2377

分类: .NET技术 网页设计 交互设计

上一篇:Rails2.1新特性之四:Partial Updates   下一篇:Rails2.1新特性之六:UTC-based Migration