from Description ActionDispatch ::Routing::Mapper::Scoping scope(*args) { || ... } Scopes a set of routes to the given default options. ActiveRecord ::Associations::CollectionProxy Scope() Returns a Relation object for the records in this association ActiveRecord ::DeprecatedFinders scope(name, body = {}, &block) ActiveRecord ::Reflection::MacroReflection#sco pe ActiveRecord ::Scoping::Named::ClassMethods scope(name, body, &block) Rake::Task#scope Array of nested namespaces names used for task lookup by this task.
method for retrieving and querying objects: it's a way to narrow a database query. def scope(name, body, &block) extension = Module.new(&block) if block singleton_class.send(:define_method, name) do |*args| scope = all.scoping { body.call(*args) } scope = scope.extending(extension) if extension scope || all end end
for defining a class method. This: Same as: SQL: scope :tabby, -> { where(coat_coloration: 'tabby') } def self.tabby where(coat_coloration: 'tabby') end SELECT “cats”.* FROM “cats” WHERE “cats”.”coat_coloration” = “tabby”;
by calling a scope on its class resembles the object constructed by a has_many declaration. These methods are also available to has_many associations. cat_palace.cats.tabby.first cat_palace.cats.tabby.kitten cat_palace.cats.tabby.count cat_palace.cats.kitten.tabby.count cat_palace.cats.tabby.each(&block)
scope in model # Use as filters by declaring has_scope in controller and apply scopes to a resource by calling apply_scopes # Send request for LOLcats class Cat < ActiveRecord::Base scope :LOL, -> { where(funny: true) } end class CatsController < ApplicationController has_scope :LOL, type: :boolean def index @cats = apply_scopes(Cat).all end end /cats?LOL=true