andela-amagana
12/3/2017 - 3:47 PM

Using scope to define class methods for a model

Syntactic sugar for defining class methods in ActiveRecord models

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 methods can then be accessed as such
Shirt.red
Shirt.dry_clean_only