ActiveRecord scopes

(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at: lawrence@krubner.com, or follow me on Twitter.

I knew this once, but forgot during the time I have not worked with Rails:

scope(name, body, &block) Link

Adds a class method for retrieving and querying objects. A scope represents a narrowing of a database query, such as where(color: :red).select(‘shirts.*’).includes(:washing_instructions).

class Shirt < ActiveRecord::Base scope :red, -> { where(color: ‘red’) }
scope :dry_clean_only, -> { joins(:washing_instructions).where(‘washing_instructions.dry_clean_only = ?’, true) }
end

The above calls to scope define class methods Shirt.red and Shirt.dry_clean_only. Shirt.red, in effect, represents the query Shirt.where(color: ‘red’).

You should always pass a callable object to the scopes defined with scope. This ensures that the scope is re-evaluated each time it is called.

Note that this is simply ‘syntactic sugar’ for defining an actual class method:

class Shirt < ActiveRecord::Base def self.red where(color: 'red') end end Unlike Shirt.find(...), however, the object returned by Shirt.red is not an Array; it resembles the association object constructed by a has_many declaration. For instance, you can invoke Shirt.red.first, Shirt.red.count, Shirt.red.where(size: 'small'). Also, just as with the association objects, named scopes act like an Array, implementing Enumerable; Shirt.red.each(&block), Shirt.red.first, and Shirt.red.inject(memo, &block) all behave as if Shirt.red really was an Array. These named scopes are composable. For instance, Shirt.red.dry_clean_only will produce all shirts that are both red and dry clean only. Nested finds and calculations also work with these compositions: Shirt.red.dry_clean_only.count returns the number of garments for which these criteria obtain. Similarly with Shirt.red.dry_clean_only.average(:thread_count).

Post external references

  1. 1
    http://api.rubyonrails.org/classes/ActiveRecord/Scoping/Named/ClassMethods.html
Source