问题描述
有一个项目我工作的,看起来像下面这样的named_scope:
There's a named_scope in a project I'm working on that looks like the following:
# 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(:找到)的作品。这显然是调用另一个名为范围(not_deleted),并应用.scope(:找到)之后。什么/如何做.scope(:找到)在这里工作。
The initial named_scope makes sense. The confusing part here is how .scope(:find) works. This is clearly calling another named scope (not_deleted), and applying .scope(:find) afterwards. What/how does .scope(:find) work here?
推荐答案
一个快速的答案
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.
因此,通过例如:
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'
或者,你可以写
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.
请注意,这已经变得越来越简单(清洁剂)的轨道3,你只写
Note that this has become simpler (cleaner) in rails 3, you would just write
scope :active_and_not_deleted, active.not_deleted
这篇关于导轨2.3.x - 请问如何ActiveRecord的工作范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!