Model catModel cat
Ellen Musick
Can Haz Scope?Can Haz Scope?
What scope?
● I'm not talking about variable scope.
● $ ri scope
What can be scoped?
Routes, ModelsModels, Rake Tasks
Implementation 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.
Scoping Models, Part 1
From ActiveRecord::Scoping::Named::ClassMethods
“scope” adds a class method for retrieving and
querying objects: it's a way to narrow a database
query.
def scope(name, body, &block)
extension = (&block) if block
(:define_method, name) do |*args|
scope = { (*args) }
scope = (extension) if extension
scope || all
end
end
Scoping Models, Part 2
● Scopes are simply 'syntactic sugar' for defining
a class method.
This:
Same as:
SQL:
scope :tabby, -> { where(coat_coloration: 'tabby') }
def
where(coat_coloration: 'tabby')
end
SELECT “cats”.* FROM “cats” WHERE “cats”.”coat_coloration” = “tabby”;
Taking advantage
(&block)
The object returned 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.
(&block)
gem 'has_scope'
Maps controller filters to resource scopes
# Define 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
Yes, model catYes, model cat
can haz haz scope.
Resources
● $ ri scope
●
ng/Named/
●
/lib/active_record/scoping/
●
html#scopes
●