ruby
28 lines · 7 steps
How Rails models wire up associations
A Product and Category pair shows how Active Record associations, validations, scopes, and helpers fit together.
Explained by
highlit
1class Product < ApplicationRecord
2 belongs_to :category, touch: true
3
4 has_many :reviews, dependent: :destroy
5
6 validates :name, presence: true
7 validates :price_cents, numericality: { greater_than: 0 }
8
9 scope :published, -> { where(published: true) }
10
11 def average_rating
12 reviews.average(:rating)&.round(1) || 0.0
13 end
14
15 def formatted_price
16 Money.new(price_cents, currency).format
17 end
18end
19
20class Category < ApplicationRecord
21 has_many :products, dependent: :restrict_with_error
22
23 validates :name, presence: true, uniqueness: true
24
25 def cache_key_with_products
26 "#{cache_key_with_version}/products-#{products.count}"
27 end
28end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Association options like touch and dependent encode cascade and cache behavior declaratively instead of in callbacks.
- 2Instance methods on a model are the right home for derived values that combine associated data.
- 3Pairing dependent: :destroy on one side with :restrict_with_error on the other defines clear deletion rules across the relationship.
Related explainers
ruby
class TasksController < ApplicationController before_action :set_project def reorder
Bulk task reordering with upsert_all in Rails
bulk-update
upsert
authorization
Intermediate
8 steps
ruby
require "openssl" require "json" require "base64"
Building signed session tokens in Ruby
hmac
authentication
cryptography
Intermediate
8 steps
ruby
require "net/http" require "json" require "uri" require "base64"
Paginating an HTTP API with a Ruby enumerator
pagination
http
enumerator
Intermediate
7 steps
ruby
class DateRangeMerger def initialize(ranges) @ranges = ranges end
Merging overlapping date ranges in Ruby
sorting
interval-merging
enumerable
Intermediate
5 steps
ruby
module SlowQueryLogger SLOW_QUERY_THRESHOLD_MS = 200.0 IGNORED_PAYLOAD_NAMES = %w[SCHEMA TRANSACTION].freeze
Logging slow SQL queries in Rails
instrumentation
logging
pub-sub
Intermediate
7 steps
ruby
require "phonelib" class PhoneNumber class InvalidNumber < StandardError; end
Wrapping phone parsing in a Ruby value object
value-object
memoization
validation
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-rails-models-wire-up-associations-explained-ruby-0d9f/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.