Rails 2.3.x - how does this ActiveRecord realm work?

There, the named_scope project in the project I'm working on looks like this:

 # 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 original named_scope makes sense. The confusing part here is how .scope (: find) works. This explicitly calls another named scope (not_deleted) and applies later .scope (: find). What / how does .scope (: find) work?

+3
source share
2 answers

Quick response

Product.not_deleted.available(args.first)

- the named area itself, formed by the union of both named areas.

scope(:find) gets conditions for the named area (or combination of areas), which you, in turn, can use to create a new named area.

So, for 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 can write

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

. , .

, () 3,

scope :active_and_not_deleted, active.not_deleted
+4

Scope - 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

, Product.find .

named_scope:

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

Object.active.scope(:find) :

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

Source: https://habr.com/ru/post/1787017/


All Articles