sajad torkamani

What are Scopes?

Scopes let you define commonly used queries as methods on models. Scopes should return ActiveRecord::Relation or nil to allow other methods and scopes to be chained.

Define scope using lambda

class Book < ApplicationRecord
  scope :out_of_print, -> { where(out_of_print: true) }
end

Call it:

Book.out_of_print
=> #<ActiveRecord::Relation> # all out of print books

Define scope that takes arguments

class Book < ApplicationRecord
  scope :costs_more_than, ->(amount) { where("price > ?", amount) }
end
Book.costs_more_than(100.10)

Define default scope

class Book < ApplicationRecord
  default_scope { where(out_of_print: false) }
end

Remove scope

Book.unscoped.load

Sources

Tagged: Rails

Leave a comment

Your email address will not be published. Required fields are marked *