Code Explainers

Code explainers tagged #scopes

ruby
class Product < ApplicationRecord
  belongs_to :category, touch: true
 
  has_many :reviews, dependent: :destroy

How Rails models wire up associations

active record associations validations
Intermediate 7 steps
ruby
class Booking < ApplicationRecord
  belongs_to :room
  belongs_to :guest
 

Guarding booking dates in a Rails model

validations associations scopes
Intermediate 5 steps
ruby
class Article < ApplicationRecord
  belongs_to :author, class_name: "User"
  has_many :taggings, dependent: :destroy
  has_many :tags, through: :taggings

How scopes compose in Rails

scopes activerecord query-composition
Intermediate 8 steps
ruby
class PaymentMethod < ApplicationRecord
  belongs_to :account
 
  encrypts :card_number, deterministic: false

How Rails encrypts sensitive payment fields

encryption validation scopes
Intermediate 9 steps
ruby
class Account < ApplicationRecord
  has_many :projects, dependent: :destroy_async
  has_many :memberships, dependent: :destroy_async
  has_many :invoices, dependent: :restrict_with_error

Safely closing an Account in Rails

associations callbacks transactions
Intermediate 9 steps
ruby
class User < ApplicationRecord
  store_accessor :preferences,
    :theme,
    :timezone,

Storing user settings in a JSON column with Rails

store_accessor json-columns validations
Intermediate 7 steps
ruby
class Subscription < ApplicationRecord
  belongs_to :account
 
  enum :status, {

Modeling subscription lifecycle in Rails

enums scopes state-management
Intermediate 8 steps
ruby
class ProductsController < ApplicationController
  def index
    @products = Product
      .includes(:category, :brand)

Building a safe filterable product index in Rails

query objects scopes strong parameters
Intermediate 8 steps
ruby
module SoftDeletable
  extend ActiveSupport::Concern
 
  included do

How a soft-delete concern works in Rails

concerns soft-delete scopes
Intermediate 8 steps
ruby
class Article < ApplicationRecord
  belongs_to :author
 
  default_scope { where(deleted_at: nil) }

How scopes compose in Rails

scopes query-composition activerecord
Intermediate 9 steps
ruby
class Employee < ApplicationRecord
  validates :name, presence: true
  validates :salary, numericality: { greater_than: 0 }
 

How STI models share behavior in Rails

single-table-inheritance inheritance method-overriding
Intermediate 8 steps