简体   繁体   English

Rails 2.3.x-此ActiveRecord范围如何工作?

[英]Rails 2.3.x - how does this ActiveRecord scope work?

There's a named_scope in a project I'm working on that looks like the following: 我正在处理的项目中有一个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)
  }

The initial named_scope makes sense. 最初的named_scope很有意义。 The confusing part here is how .scope(:find) works. 这里令人困惑的部分是.scope(:find)的工作方式。 This is clearly calling another named scope (not_deleted), and applying .scope(:find) afterwards. 显然,这将调用另一个命名范围(未删除),然后再应用.scope(:find)。 What/how does .scope(:find) work here? .scope(:find)在这里做什么/如何工作?

A quick answer 快速解答

Product.not_deleted.available(args.first)

is a named-scope itself, formed by combining both named scopes. 是一个本身由两个命名范围合并而成的命名范围。

scope(:find) gets the conditions for a named-scope (or combination of scopes), which you can in turn use to create a new named-scope. scope(:find)获取命名范围(或范围的组合)的条件,您可以依次使用它们创建新的命名范围。

So by example: 因此,通过示例:

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

then you write 然后你写

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

or, you could write 或者,你可以写

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

which is identical. 这是相同的。 I hope that makes it clear. 我希望这一点很清楚。

Note that this has become simpler (cleaner) in rails 3, you would just write 注意,这在rails 3中变得更简单(更干净),您只需编写

scope :active_and_not_deleted, active.not_deleted

Scope is a method on ActiveRecord::Base that returns the current scope for the method passed in (what would actually be used to build the query if you were to run it at this moment). 范围是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

So in your example, the lambda returns the scope for a Product.find call after merging all the other named scopes. 因此,在您的示例中,lambda在合并所有其他命名的范围之后返回Product.find调用的范围。

I have a named_scope: 我有一个named_scope:

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

In my console output, Object.active.scope(:find) returns: 在我的控制台输出中, Object.active.scope(:find)返回:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM