Method: Mongoid::Scopable::ClassMethods#scope

Defined in:
lib/mongoid/scopable.rb

#scope(name, value, &block) ⇒ Object

Create a scope that can be accessed from the class level or chained to criteria by the provided name.

Examples:

Create named scopes.


class Person
  include Mongoid::Document
  field :active, type: Boolean
  field :count, type: Integer

  scope :active, -> { where(active: true) }
  scope :at_least, ->(count){ where(:count.gt => count) }
end

Parameters:

  • name (Symbol)

    The name of the scope.

  • conditions (Proc)

    The conditions of the scope.

Raises:

Since:

  • 1.0.0



142
143
144
145
146
147
148
149
150
151
# File 'lib/mongoid/scopable.rb', line 142

def scope(name, value, &block)
  normalized = name.to_sym
  check_scope_validity(value)
  check_scope_name(normalized)
  _declared_scopes[normalized] = {
    scope: value,
    extension: Module.new(&block)
  }
  define_scope_method(normalized)
end