Rails Scopes reference
25 April 2022 (Updated 25 April 2022)
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
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment