2011-04-26 48 views
0

我想基於GET參數在ActiveRecord中構建一個查詢,並使用named_scope。我想我一定鏈範圍和添加基於GET PARAM的使用狀況,但我擔心這會積勞成疾分貝,每個查詢部分發送一個新的查詢,添加:Rails 2.3.x - 懶惰的數據庫查詢

# in model 
named_scope :sorted, :order => 'title, author' 
named_scope :archived, :conditions => { :is_archived => true } 
named_scope :by_date, lambda { |date| { :conditions => [ 'updated_at = ?', date ] } } 

# in controller/helper 
@articles = Article.sorted.all 
@articles = @articles.by_date(params[:date]) if params[:date] 
@articles = @articles.archived if params[:archived] == '1' 

我想過的另一種選擇正在構建一個鏈接字符串的方法,然後使用Object#send發送給對象,但是當named_scope接收到參數(如by_date)時,這似乎有點髒並且有些問題。我意識到我可以構建一個查詢字符串與:conditions => ...,ActiveRecord::Base#find一起使用,但我認爲我會先試着用named_scope來查看是否有可能對後者進行懶惰查詢。有關如何使用named_scope執行此操作並且沒有受到查詢轟炸的數據庫的任何建議?謝謝。

回答

1

可以使拉姆達更聰明

# in model 
named_scope :sorted, :order => 'title, author' 
named_scope :archived, lambda { |is_archived| (is_archived == 1) ? {:conditions => {:is_archived => true}} : {}} 
named_scope :by_date, lambda { |date| date.nil? ? {} : { :conditions => [ 'updated_at = ?', date ]}} 

# in controller/helper 
@articles = Article.by_date(params[:date]).archived(params[:archived]).sorted