2011-01-21 32 views
3

有一個項目我工作的一個named_scope如下所示:Rails 2.3.x - 這個ActiveRecord作用域如何工作?

# default product scope only lists available and non-deleted products 
    ::Product.named_scope :active,  lambda { |*args| 
    Product.not_deleted.available(args.first).scope(:find) 
    } 

初始named_scope是有道理的。這裏令人困惑的部分是.scope(:find)是如何工作的。這顯然調用另一個命名作用域(not_deleted),然後應用.scope(:find)。 .scope(:find)在這裏工作的是什麼/怎麼樣?

回答

4

一個快速的回答

Product.not_deleted.available(args.first) 

是一個名爲範圍的本身,通過形成結合兩個命名範圍。

scope(:find)獲取命名範圍(或範圍組合)的條件,您可以依次使用該範圍創建新的命名範圍。

因此,通過例如:

named_scope :active,  :conditions => 'active = true' 
named_scope :not_deleted, :conditions => 'deleted = false' 

那麼你就寫

named_scope :active_and_not_deleted, :conditions => 'active = true and deleted = false' 

或者,你可以寫

named_scope :active_and_not_deleted, lambda { self.active.not_deleted.scope(:find) } 

是相同的。我希望能夠說清楚。

注意,這在軌道3已經變得越來越簡單(清潔劑),你會只寫

scope :active_and_not_deleted, active.not_deleted 
1

作用域是ActiveRecord :: Base上的一個方法,它返回傳入的方法的當前作用域(如果此時正在運行,實際將用於構建查詢)。

# Retrieve the scope for the given method and optional key. 
def scope(method, key = nil) #:nodoc: 
    if current_scoped_methods && (scope = current_scoped_methods[method]) 
    key ? scope[key] : scope 
    end 
end 

因此,在你的榜樣,在lambda返回合併其他所有的命名範圍後Product.find通話範圍。

我有一個named_scope:

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

在我的控制檯輸出,Object.active.scope(:find)回報:

{:conditions => {:active => true}} 
相關問題