[英]Rails 2.3.x - how does this ActiveRecord scope work?
我正在處理的項目中有一個named_scope,如下所示:
# 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)的工作方式。 顯然,這將調用另一個命名范圍(未刪除),然后再應用.scope(:find)。 .scope(:find)在這里做什么/如何工作?
快速解答
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) }
這是相同的。 我希望這一點很清楚。
注意,這在rails 3中變得更簡單(更干凈),您只需編寫
scope :active_and_not_deleted, active.not_deleted
范圍是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}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.