2009-12-16 39 views
4

我知道你可以創建Rails的命名範圍,它允許你指定,然後可以在以後建立在條件:我可以在Rails中創建* un *命名範圍嗎?

named_scope :active, :conditions => {:active => true} 

... 

MyModel.active.find(...) 

這個工程通過創建不計算,直到後來上的代理對象。我想知道的是,如果有可能創建一個名爲範圍的動態un

我的意思是,有沒有一種方法「富」與我可以去

scope = MyModel.foo(:conditions => {:target_id => 4}) 

,然後通過scope各地的代理對象,我可以做更多的.find S或其他範圍的電話嗎?

回答

7

是,檢查Anonymous Scopes

def find_products 
    scope = Product.scoped({}) 
    scope = scope.conditions "products.name LIKE ?", "%#{keywords}%" unless keywords.blank? 
    scope = scope.conditions "products.price >= ?", minimum_price unless minimum_price.blank? 
    scope = scope.conditions "products.price <= ?", maximum_price unless maximum_price.blank? 
    scope = scope.conditions "products.category_id = ?", category_id unless category_id.blank? 
    scope 
end 
+1

這是完美的,它只能在一個文件中記錄[http://api.rubyonrails.org/classes/ActiveRecord/NamedScope.html]我無法想象否則我會看 – Gareth

相關問題