声明:JavaEye新闻文章的版权属于JavaEye网站所有,严禁任何网站转载本文,否则必将追究法律责任!
Nick Kallen的广受欢迎的has_finder插件将会被加入到Rails 2.x版本中,以named_scope方式出现。
你所喜欢的has_finder所有优点现在都被named_scope提供——还附带一些额外的优点。User.all成了User.find(:all)的另一种写法。
高级特性:
那些对discriminating有更多需求的,别忘了还有has_finder里的一些技巧。
传递参数
在运行时,将参数传递给named scope中的特定条件。
扩展Named Scope
扩展named scipes(一种类似集合扩展的风格)
匿名Scopes
你可以在第一个类使用scoped方法来传递scopes
name_scope是一个非常不错的功能,如果你还没开始使用它,请试着尝试下,你会发现再也离不开它了。万分感谢Nick
Rails2.1中的新东西之四: Partial Updates
Rails2.1中的新东西之三: Dirty Objects
Rails2.1中的新东西之二: Gem Dependencies
Rails2.1中的新东西之一: has-one-through
class User < ActiveRecord::Base
named_scope :active, :conditions => {:active => true}
named_scope :inactive, :conditions => {:active => false}
named_scope :recent, lambda { { :conditions => ['created_at > ?', 1.week.ago] } }
end
# Standard usage
User.active # same as User.find(:all, :conditions => {:active => true})
User.inactive # same as User.find(:all, :conditions => {:active => false})
User.recent # same as User.find(:all, :conditions => ['created_at > ?', 1.week.ago])
# They're nest-able too!
User.active.recent
# same as:
# User.with_scope(:conditions => {:active => true}) do
# User.find(:all, :conditions => ['created_at > ?', 1.week.ago])
# end
你所喜欢的has_finder所有优点现在都被named_scope提供——还附带一些额外的优点。User.all成了User.find(:all)的另一种写法。
高级特性:
那些对discriminating有更多需求的,别忘了还有has_finder里的一些技巧。
传递参数
在运行时,将参数传递给named scope中的特定条件。
class User < ActiveRecord::Base
named_scope :registered, lambda { |time_ago| { :conditions => ['created_at > ?', time_ago] }
end
User.registered 7.days.ago # same as User.find(:all, :conditions => ['created_at > ?', 7.days.ago])
扩展Named Scope
扩展named scipes(一种类似集合扩展的风格)
class User < ActiveRecord::Base
named_scope :inactive, :conditions => {:active => false} do
def activate
each { |i| i.update_attribute(:active, true) }
end
end
end
# Re-activate all inactive users
User.inactive.activate
匿名Scopes
你可以在第一个类使用scoped方法来传递scopes
# Store named scopes
active = User.scoped(:conditions => {:active => true})
recent = User.scoped(:conditions => ['created_at > ?', 7.days.ago)
# Which can be combined
recent_active = recent.active
# And operated upon
recent_active.each { |u| ... }
name_scope是一个非常不错的功能,如果你还没开始使用它,请试着尝试下,你会发现再也离不开它了。万分感谢Nick
Rails2.1中的新东西之四: Partial Updates
Rails2.1中的新东西之三: Dirty Objects
Rails2.1中的新东西之二: Gem Dependencies
Rails2.1中的新东西之一: has-one-through
来自:ryandaigle.com


评论 共 0 条 发表评论