In Part 3 we built study plans. A plan alone isn't much use, so now we give it structure:
- A study plan ("Learn SQL") has many topics ("Joins", "Indexes").
- A topic has many study sessions, the actual blocks of time you sit down and study.
This post is about modeling data: associations, validations, callbacks and scopes. It's the most "Active Record" post in the series, and the one that makes the rest of the app easy to write.
What you'll learn
- Designing three connected tables
-
has_many :throughandhas_one :through - Validations, including a custom one
- A
before_validationcallback - Scopes with and without arguments
- Avoiding N+1 queries with
includes - Keeping the "users only see their own data" rule across three levels of nesting
Step 1: The shape of the data
User ──< StudyPlan ──< Topic ──< StudySession
Each arrow means "has many". A user has many plans, a plan has many topics, a topic has many sessions. Each child table holds the foreign key to its parent.
Step 2: Generate the models
bin/rails generate model Topic name:string description:text estimated_hours:integer position:integer study_plan:references
bin/rails generate model StudySession title:string notes:text started_at:datetime finished_at:datetime topic:references
Edit the two migrations before running them:
# topics
t.string :name, null: false
t.integer :estimated_hours, null: false
t.integer :position, null: false
# study_sessions
t.string :title, null: false
t.datetime :started_at, default: -> { "CURRENT_TIMESTAMP" }
bin/rails db:migrate
-
null: falsemakes the database refuse missing names, hours and positions. -
started_atdefaults to the moment the row is created, so a session starts when you start it. -
finished_atis nullable on purpose: aNULLfinish time means the session is still running. That one decision drives most of the code below.
Step 3: Associations
# app/models/study_plan.rb
class StudyPlan < ApplicationRecord
belongs_to :user
has_many :topics, dependent: :destroy
validates :name, presence: true
end
# app/models/topic.rb
class Topic < ApplicationRecord
belongs_to :study_plan
has_many :study_sessions, dependent: :destroy
end
# app/models/study_session.rb
class StudySession < ApplicationRecord
belongs_to :topic
has_one :study_plan, through: :topic
end
# app/models/user.rb (add two lines)
has_many :topics, through: :study_plans
has_many :study_sessions, through: :topics
The new part is through. It lets you jump across tables:
-
user.topicsmeans "all topics in all of this user's plans". -
user.study_sessionsmeans "all sessions in all of those topics". -
study_session.study_planmeans "the plan of this session's topic".
Rails writes the SQL joins for you. In the console:
user = User.first
user.study_sessions.to_sql
# SELECT "study_sessions".* FROM "study_sessions"
# INNER JOIN "topics" ON ...
# INNER JOIN "study_plans" ON ...
# WHERE "study_plans"."user_id" = 1
Now remember the rule from Part 3: always start from the current user. With these associations, one line does it for any level:
Current.user.topics.find(params[:id])
Current.user.study_sessions.find(params[:id])
If the record belongs to someone else, find raises RecordNotFound and Rails answers 404.
Step 4: Validations and a callback
class Topic < ApplicationRecord
belongs_to :study_plan
has_many :study_sessions, dependent: :destroy
validates :name, :estimated_hours, presence: true
validates :estimated_hours, numericality: { greater_than: 0 }
before_validation :set_position, on: :create
private
def set_position
self.position = (study_plan.topics.maximum(:position) || 0) + 1
end
end
-
numericality: { greater_than: 0 }rejects 0, negative numbers and non-numbers. -
before_validation :set_position, on: :createis a callback: Rails runs this method automatically at a certain moment in the object's life, here just before validating a new topic. It finds the highest existingpositionin the plan (maximumreturnsnilfor an empty plan, hence|| 0) and adds one. Topics stay ordered without anyone typing a number. - note: position can be used later to allow user to re-order topics based on his own priority not based on the order of creation.
Try it:
plan = StudyPlan.first
a = plan.topics.create!(name: "Joins", estimated_hours: 3)
b = plan.topics.create!(name: "Indexes", estimated_hours: 2)
[a.position, b.position] # => [1, 2]
Callbacks are powerful and a little dangerous: they run "invisibly". Use them for small, predictable housekeeping like this, and be careful once they start sending emails or touching other records. We'll meet that in Part 8.
Step 5: Study sessions: a custom validation and scopes
class StudySession < ApplicationRecord
belongs_to :topic
has_one :study_plan, through: :topic
validate :only_one_session_active, on: :create
scope :active, -> { where(finished_at: nil) }
scope :completed_at, ->(date) { where(finished_at: date.all_day) }
scope :of_user, ->(user) { joins(topic: :study_plan).where(study_plans: { user_id: user.id }) }
private
def only_one_session_active
return if topic.study_sessions.active.empty?
errors.add(:base, "There is already an active study session for this topic.")
end
end
A custom validation
validate (singular) takes the name of your own method. If the method adds something to errors, the record is invalid. Here, a topic can't have two sessions running at once. errors.add(:base, ...) attaches the message to the whole record instead of one field.
Scopes: named, reusable queries
A scope gives a name to a query you'll use again:
StudySession.active # sessions with no finish time
StudySession.completed_at(Date.today) # finished today
StudySession.of_user(user) # sessions belonging to a user
Notice three things:
- A scope can take arguments:
completed_attakes a date.date.all_dayis a range from midnight to 23:59:59, sowhere(finished_at: range)becomes a SQLBETWEEN. - Scopes chain:
StudySession.of_user(user).activecombines both conditions. -
of_userusesjoins(topic: :study_plan)to hop from sessions to topics to plans, then filters on the plan'suser_id. (Since we declaredhas_many :through,user.study_sessionsgives the same result. Writing it as a scope shows you how a join works, and it's handy when you only have a user object and want to start from the sessions side.)
Step 6: Routes and controllers
# config/routes.rb
resources :study_plans
resources :topics
resources :study_sessions do
patch :complete, on: :member
end
root "dashboard#show"
The patch :complete, on: :member line adds a custom action on one specific session: PATCH /study_sessions/:id/complete, with the helper complete_study_session_path(session). Use member for "an action on one record" and collection for "an action on the whole list" (you'll see that one in Part 7).
Why resources :topics and not nested inside plans? It keeps URLs and helpers short: edit_topic_path(topic). The one place we need the parent is when creating, and we pass it as a parameter: new_topic_path(study_plan_id: plan.id). (Nested routes like /study_plans/1/topics are a valid alternative, so use whichever you find clearer.)
# app/controllers/topics_controller.rb
class TopicsController < ApplicationController
before_action :find_study_plan!, only: %i[new create]
before_action :find_topic!, only: %i[edit update destroy]
def new
@topic = @study_plan.topics.new
end
def create
@topic = @study_plan.topics.new(topic_params)
if @topic.save
redirect_to study_plan_path(@study_plan), notice: "Topic created successfully."
else
flash.now[:alert] = @topic.errors.full_messages.join(", ")
render :new, status: :unprocessable_content
end
end
def edit
end
def update
if @topic.update(topic_params)
redirect_to study_plan_path(@topic.study_plan), notice: "Topic updated successfully."
else
flash.now[:alert] = @topic.errors.full_messages.join(", ")
render :edit, status: :unprocessable_content
end
end
def destroy
@topic.destroy
redirect_to study_plan_path(@topic.study_plan), notice: "Topic deleted successfully."
end
private
def topic_params
params.expect(topic: [ :name, :description, :estimated_hours ])
end
def find_study_plan!
plan_id = params[:study_plan_id] || params.expect(topic: :study_plan_id)[:study_plan_id]
@study_plan = Current.user.study_plans.find(plan_id)
end
def find_topic!
@topic = Current.user.topics.find(params.expect(:id))
end
end
Three patterns here are worth stealing:
-
before_actionruns a method before the listed actions, so we write each lookup once. -
Look up the parent through the user, then build the child through the parent:
Current.user.study_plans.find(...)followed by@study_plan.topics.new(...). We never let the form decide which plan the topic belongs to. If someone sends another user'sstudy_plan_id, the lookup raises a 404. That's whystudy_plan_idis not intopic_params. -
flash.now(instead offlash) shows a message only on this render, not on the next request. Useflash.nowwithrenderandflashwithredirect_to.
StudySessionsController has the same structure. A session is created under a topic the user owns, and found again with Current.user.study_sessions.find. It adds one action:
def complete
if @study_session.update(finished_at: Time.current)
redirect_to study_plan_path(@study_session.study_plan), notice: "Study session completed successfully."
else
flash.now[:alert] = @study_session.errors.full_messages.join(", ")
render :edit, status: :unprocessable_content
end
end
Completing a session is just setting finished_at. Since active means finished_at: nil, the session instantly stops being active.
Step 7: A page for one plan
Part 3 skipped show. Now there's something to show:
# study_plans_controller.rb
def show
@study_plan = Current.user.study_plans.find(params.expect(:id))
end
<%# app/views/study_plans/show.html.erb %>
<h1 class="font-bold text-4xl"><%= @study_plan.name %></h1>
<%= link_to "Edit", edit_study_plan_path(@study_plan) %>
<p>Description: <%= @study_plan.description %></p>
<p>Daily hours: <%= @study_plan.daily_hour %></p>
<h2 class="font-bold text-2xl mt-6">Topics</h2>
<ul>
<% @study_plan.topics.each do |topic| %>
<li>
<%= render "topics/topic", topic: topic %>
</li>
<% end %>
</ul>
<%= link_to "Add a Topic", new_topic_path(study_plan_id: @study_plan.id) %>
render "topics/topic", topic: topic renders a partial, a reusable snippet stored in app/views/topics/_topic.html.erb (partials always start with an underscore):
<strong><%= topic.name %></strong> - <%= topic.description %>
(Estimated hours: <%= topic.estimated_hours %>)
<%= link_to "Edit", edit_topic_path(topic) %>
<%= link_to "Delete", topic_path(topic), data: { turbo_method: :delete, turbo_confirm: "Are you sure?" } %>
<% if topic.study_sessions.active.empty? %>
<%= link_to "Start a study session", new_study_session_path(topic_id: topic.id) %>
<% end %>
<ul>Study Sessions:
<% topic.study_sessions.each do |study_session| %>
<li><%= render "study_sessions/session", session: study_session %></li>
<% end %>
</ul>
See how the scope pays off: topic.study_sessions.active.empty? reads like English. We only show the "Start" link when nothing is running, and the model validation guarantees it even if someone forges the request.
Step 8: The dashboard and the N+1 problem
# app/controllers/dashboard_controller.rb
class DashboardController < ApplicationController
def show
@study_plans = Current.user.study_plans
@ongoing_study_sessions =
StudySession.of_user(Current.user).active.includes(topic: :study_plan)
@completed_today_sessions =
StudySession.of_user(Current.user).completed_at(Date.current).includes(topic: :study_plan)
end
end
Look at the chain: of_user(...).active.includes(...). Three small scopes combine into a precise question.
What does includes do? In the view we print study_session.topic.study_plan.name for each session. Without includes, Rails runs one query for the sessions, then one more query per session for its topic, and another for its plan. Ten sessions means 21 queries. That's the N+1 problem. With includes(topic: :study_plan), Rails loads all the topics in one query and all the plans in another: 3 queries total, however many sessions you have.
<h2 class="font-bold text-2xl mt-6">Active Study Sessions</h2>
<ul>
<% @ongoing_study_sessions.each do |study_session| %>
<li>
<p><%= study_session.topic.study_plan.name %> - <%= study_session.topic.name %></p>
<%= render "study_sessions/session", session: study_session %>
</li>
<% end %>
</ul>
<h2 class="font-bold text-2xl mt-6">Study Sessions Completed Today</h2>
<ul>
<% @completed_today_sessions.each do |study_session| %>
<li>
<p><%= study_session.topic.study_plan.name %> - <%= study_session.topic.name %></p>
<%= render "study_sessions/session", session: study_session %>
</li>
<% end %>
</ul>
Use Date.current rather than Date.today. current respects Rails' configured time zone. We'll make that per-user in Part 10.
Run bin/dev and try it: create a plan, add topics, start a session, end it, and watch it move from "Active" to "Completed Today".
✅ How to test this
Manual checks:
- Start a session on a topic. The "Start a study session" link should disappear.
- In the Rails console, try to cheat:
Topic.first.study_sessions.create!(title: "second")should raiseRecordInvalid. - Log in as a second user and open
/topics/<id of first user's topic>/edit. You should get a 404.
Automated tests. test/models/topic_test.rb:
require "test_helper"
class TopicTest < ActiveSupport::TestCase
setup do
user = User.create!(email_address: "me@example.com", password: "secret123")
@plan = user.study_plans.create!(name: "Learn SQL")
end
test "requires a name and positive estimated hours" do
assert_not @plan.topics.build(name: "", estimated_hours: 1).valid?
assert_not @plan.topics.build(name: "Joins", estimated_hours: 0).valid?
assert @plan.topics.build(name: "Joins", estimated_hours: 1).valid?
end
test "assigns increasing positions" do
first = @plan.topics.create!(name: "Joins", estimated_hours: 3)
second = @plan.topics.create!(name: "Indexes", estimated_hours: 2)
assert_equal [ 1, 2 ], [ first.position, second.position ]
end
test "is deleted with its plan, along with its sessions" do
topic = @plan.topics.create!(name: "Joins", estimated_hours: 3)
topic.study_sessions.create!(title: "Read chapter 1")
assert_difference [ "Topic.count", "StudySession.count" ], -1 do
@plan.destroy
end
end
end
test/models/study_session_test.rb:
require "test_helper"
class StudySessionTest < ActiveSupport::TestCase
setup do
@user = User.create!(email_address: "me@example.com", password: "secret123")
plan = @user.study_plans.create!(name: "Learn SQL")
@topic = plan.topics.create!(name: "Joins", estimated_hours: 3)
end
test "only one session can be active per topic" do
@topic.study_sessions.create!(title: "First")
second = @topic.study_sessions.build(title: "Second")
assert_not second.valid?
assert_includes second.errors[:base], "There is already an active study session for this topic."
end
test "a new session can start after the previous one is finished" do
@topic.study_sessions.create!(title: "First", finished_at: Time.current)
assert @topic.study_sessions.build(title: "Second").valid?
end
test "active returns only unfinished sessions" do
running = @topic.study_sessions.create!(title: "Running")
@topic.study_sessions.create!(title: "Done", finished_at: Time.current)
assert_equal [ running ], StudySession.active.to_a
end
test "completed_at returns sessions finished on that day" do
done = @topic.study_sessions.create!(title: "Done", finished_at: Time.current)
@topic.study_sessions.create!(title: "Old", finished_at: 3.days.ago)
assert_equal [ done ], StudySession.completed_at(Date.current).to_a
end
test "of_user returns only that user's sessions" do
mine = @topic.study_sessions.create!(title: "Mine")
other = User.create!(email_address: "other@example.com", password: "secret123")
other_topic = other.study_plans.create!(name: "X").topics.create!(name: "Y", estimated_hours: 1)
other_topic.study_sessions.create!(title: "Theirs")
assert_equal [ mine ], StudySession.of_user(@user).to_a
end
end
And the most important controller test, test/controllers/topics_controller_test.rb:
require "test_helper"
class TopicsControllerTest < ActionDispatch::IntegrationTest
setup do
@user = User.create!(email_address: "me@example.com", password: "secret123")
@other = User.create!(email_address: "other@example.com", password: "secret123")
@plan = @user.study_plans.create!(name: "Learn SQL")
@others_plan = @other.study_plans.create!(name: "Not yours")
@others_topic = @others_plan.topics.create!(name: "Secret", estimated_hours: 1)
post session_path, params: { email_address: "me@example.com", password: "secret123" }
end
test "creates a topic inside my plan" do
assert_difference -> { @plan.topics.count }, 1 do
post topics_path, params: { study_plan_id: @plan.id, topic: { name: "Joins", estimated_hours: 3 } }
end
end
test "cannot add a topic to someone else's plan" do
assert_no_difference "Topic.count" do
post topics_path, params: { study_plan_id: @others_plan.id, topic: { name: "Joins", estimated_hours: 3 } }
end
assert_response :not_found
end
test "cannot edit or delete someone else's topic" do
get edit_topic_path(@others_topic)
assert_response :not_found
assert_no_difference "Topic.count" do
delete topic_path(@others_topic)
end
assert_response :not_found
end
end
bin/rails test
The second and third controller tests are the point of this post's security rule, and they will catch you if anyone ever "simplifies" Current.user.topics.find to Topic.find.
Common mistakes
-
N+1 queries. The page works but the log shows dozens of near-identical
SELECTs. Addincludesfor anything you call a method chain on inside a loop. (Thebulletgem can warn you automatically in development.) -
Callback order surprises.
before_validationruns beforevalid?, soset_positionneeds thestudy_planto already be set. Build children through the parent (plan.topics.new) and it always is. -
Permitting foreign keys. Putting
study_plan_idortopic_idin strong params lets a user attach records to someone else's data. Take the parent from a scoped lookup instead. -
has_many :throughwithout the middle association.has_many :topics, through: :study_plansonly works ifhas_many :study_plansis declared first. -
A scope that returns
nil. Scopes always return a relation, so they chain. If a scope's lambda returnsnil, Rails returnsallinstead. Be careful with conditional logic inside one.
One honest limitation
Our "only one active session per topic" rule is checked in Ruby. If two requests arrive at the exact same moment, both can pass the check and both save. A validation can't prevent that, only the database can. In Part 14 we'll add a unique index for it. Until then, remember: validations are for friendly messages, constraints are for guarantees.
Recap
- Three tables connected by
belongs_to/has_many;throughjumps across levels. - Validations (including custom ones) protect your data; callbacks do small automatic work.
- Scopes name your queries and chain together;
includesstops N+1. - Scoping lookups through
Current.userkeeps every level private to its owner. - A
NULLfinish time modelled "still running" without any extra column.
Next up
Right now, every click reloads the whole page. In Part 5 we add Hotwire: Turbo Frames and Turbo Streams, so adding a topic or finishing a session updates just the part of the page that changed.
Top comments (0)