Code Explainers

Code explainers tagged #activerecord

ruby
class Author < ApplicationRecord
  has_many :posts
 
  scope :with_post_stats, -> {

Aggregating post stats in a Rails scope

scopes sql-aggregation left-join
Intermediate 8 steps
ruby
class Order < ApplicationRecord
  belongs_to :customer
  has_many :line_items
  has_many :products, through: :line_items

How scopes compose in a Rails model

scopes activerecord subqueries
Intermediate 7 steps
ruby
module Paginatable
  extend ActiveSupport::Concern
 
  private

A reusable pagination concern in Rails

pagination concerns http-headers
Intermediate 8 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 Registration < ApplicationRecord
  belongs_to :event
 
  validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }

Validating registrations in Rails

validations i18n error-handling
Intermediate 8 steps
ruby
class User < ApplicationRecord
  has_secure_password
 
  normalizes :email, with: ->(email) { email.strip.downcase }

Normalizing user input in Rails models

normalization validation data integrity
Intermediate 6 steps
ruby
class Subscription < ApplicationRecord
  belongs_to :account
 
  enum :status, {

Modeling subscription lifecycle in Rails

enums scopes state-management
Intermediate 8 steps
ruby
class InactiveAccountCleanup
  BATCH_SIZE = 500
  INACTIVITY_THRESHOLD = 18.months
 

Batch-processing dormant users in Rails

batch-processing activerecord service-object
Intermediate 9 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