Code Explainers

Code explainers tagged #associations

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
module ProductsHelper
  def cached_product_row(product)
    cache [product, current_user.role] do
      render partial: "products/row", locals: { product: product }

Russian doll caching that busts itself in Rails

fragment-caching cache-invalidation associations
Intermediate 4 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 ArticleSerializer < ActiveModel::Serializer
  attributes :id, :title, :slug, :excerpt, :reading_time, :published_at, :url
 
  belongs_to :author, serializer: UserSerializer

Shaping API output with ActiveModel::Serializer in Rails

serialization json api computed attributes
Intermediate 9 steps
ruby
class Comment < ApplicationRecord
  belongs_to :post
  belongs_to :author, class_name: "User"
 

Live-updating comments with Turbo in Rails

turbo-streams callbacks associations
Intermediate 8 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 CreateCommentsWithCounterCache < ActiveRecord::Migration[7.1]
  def change
    create_table :posts do |t|
      t.string :title, null: false

How counter caches work in Rails

counter-cache migrations associations
Intermediate 6 steps