`
muyu
  • 浏览: 218597 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

named_scope的用法及如何paginate

阅读更多

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

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)的别名,可以之间使用。

 

高级

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

 

传递参数

 

给你命名的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 Extensions

 

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

 

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

 

 

匿名 scope

 

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

 

# 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| ... }

 

 

(译者注:这和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结合起来?

 

class Product < ActiveRecord::Base
  
  named_scope :online, :conditions => {:status => 1}, :include => [:variants, :catalogue_images, :categories]
  named_scope :from_category_ids, lambda { |cat_ids| {:conditions => "categories_products.category_id IN (#{cat_ids})", :include => :categories }}

end

class CatalogueController < RaidBase
  
  def category
    @products = Product.from_category_ids(@category.leaf_ids).online.paginate :page => params[:page], :per_page => params[:per_page]
  end
end

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

分享到:
评论
2 楼 pure 2008-11-14  
非常好~又省很多事了!
1 楼 yangzhihuan 2008-10-11  
那就是可以直接对named_scope调用paginate方法进行分页,这个相当的方便.

相关推荐

Global site tag (gtag.js) - Google Analytics