Ruby rails: scopes

From wikinotes
Revision as of 18:13, 9 April 2020 by Will (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Scopes are custom queries that you define inside your Rails models.
They return ActiveRecord::Relation objects. Scopes can be chained together.

scopes tutorial https://www.rubyguides.com/2019/10/scopes-in-ruby-on-rails/
class Fruit < ApplicationRecord
  scope :with_juice, -> { where("juice > 0") }
  scope :with_round_shape, -> { where("shape == 'round'") }   # <--(NOTE - syntax may be incorrect)
end

Fruit.with_juice.with_round_shape.first(3)