笔记:named_scope的用法

转自 muyu 的bolg, 学习并记录以备日后查询使用。

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

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

 

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

 

 

 

你可能感兴趣的:(ActiveRecord)