Code Explainers

Code explainers tagged #validations

ruby
class Order < ApplicationRecord
  include AASM
 
  belongs_to :warehouse

Modeling an order lifecycle with AASM in Rails

state machine guards callbacks
Intermediate 10 steps
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 CreateOrderItems < ActiveRecord::Migration[7.1]
  def change
    create_table :order_items do |t|
      t.references :order, null: false, foreign_key: { on_delete: :cascade }

Enforcing order-item integrity in Rails

migrations foreign-keys validations
Intermediate 7 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
  store_accessor :preferences,
    :theme,
    :timezone,

Storing user settings in a JSON column with Rails

store_accessor json-columns validations
Intermediate 7 steps
ruby
class Survey < ApplicationRecord
  has_many :questions, dependent: :destroy
  has_many :respondents, dependent: :nullify
 

Nested survey forms in Rails

nested-attributes validations associations
Intermediate 9 steps
ruby
class Post < ApplicationRecord
  before_validation :generate_slug, on: :create
 
  validates :slug, presence: true, uniqueness: true

How a Rails model builds unique slugs

slugs callbacks validations
Intermediate 7 steps
ruby
class Article < ApplicationRecord
  before_validation :generate_slug, on: :create
 
  validates :slug, presence: true, uniqueness: true,

How URL slugs work in Rails

callbacks validations slugs
Intermediate 7 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
ruby
class RegistrationForm
  include ActiveModel::Model
  include ActiveModel::Attributes
 

How a Rails form object spans two models

form object validations transactions
Intermediate 7 steps