DEV Community

Cover image for Learn Rails 8 by Building Study Flow, Part 4: Associations, Scopes and Callbacks
Shrouk Abozeid
Shrouk Abozeid

Posted on AI-assisted

Learn Rails 8 by Building Study Flow, Part 4: Associations, Scopes and Callbacks

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 :through and has_one :through
  • Validations, including a custom one
  • A before_validation callback
  • 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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" }
Enter fullscreen mode Exit fullscreen mode
bin/rails db:migrate
Enter fullscreen mode Exit fullscreen mode
  • null: false makes the database refuse missing names, hours and positions.
  • started_at defaults to the moment the row is created, so a session starts when you start it.
  • finished_at is nullable on purpose: a NULL finish 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
Enter fullscreen mode Exit fullscreen mode
# app/models/topic.rb
class Topic < ApplicationRecord
  belongs_to :study_plan
  has_many :study_sessions, dependent: :destroy
end
Enter fullscreen mode Exit fullscreen mode
# app/models/study_session.rb
class StudySession < ApplicationRecord
  belongs_to :topic
  has_one :study_plan, through: :topic
end
Enter fullscreen mode Exit fullscreen mode
# app/models/user.rb  (add two lines)
has_many :topics, through: :study_plans
has_many :study_sessions, through: :topics
Enter fullscreen mode Exit fullscreen mode

The new part is through. It lets you jump across tables:

  • user.topics means "all topics in all of this user's plans".
  • user.study_sessions means "all sessions in all of those topics".
  • study_session.study_plan means "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
Enter fullscreen mode Exit fullscreen mode

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])
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  • numericality: { greater_than: 0 } rejects 0, negative numbers and non-numbers.
  • before_validation :set_position, on: :create is 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 existing position in the plan (maximum returns nil for 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]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Notice three things:

  • A scope can take arguments: completed_at takes a date. date.all_day is a range from midnight to 23:59:59, so where(finished_at: range) becomes a SQL BETWEEN.
  • Scopes chain: StudySession.of_user(user).active combines both conditions.
  • of_user uses joins(topic: :study_plan) to hop from sessions to topics to plans, then filters on the plan's user_id. (Since we declared has_many :through, user.study_sessions gives 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"
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Three patterns here are worth stealing:

  1. before_action runs a method before the listed actions, so we write each lookup once.
  2. 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's study_plan_id, the lookup raises a 404. That's why study_plan_id is not in topic_params.
  3. flash.now (instead of flash) shows a message only on this render, not on the next request. Use flash.now with render and flash with redirect_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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
<%# 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) %>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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:

  1. Start a session on a topic. The "Start a study session" link should disappear.
  2. In the Rails console, try to cheat: Topic.first.study_sessions.create!(title: "second") should raise RecordInvalid.
  3. 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
bin/rails test
Enter fullscreen mode Exit fullscreen mode

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. Add includes for anything you call a method chain on inside a loop. (The bullet gem can warn you automatically in development.)
  • Callback order surprises. before_validation runs before valid?, so set_position needs the study_plan to already be set. Build children through the parent (plan.topics.new) and it always is.
  • Permitting foreign keys. Putting study_plan_id or topic_id in strong params lets a user attach records to someone else's data. Take the parent from a scoped lookup instead.
  • has_many :through without the middle association. has_many :topics, through: :study_plans only works if has_many :study_plans is declared first.
  • A scope that returns nil. Scopes always return a relation, so they chain. If a scope's lambda returns nil, Rails returns all instead. 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; through jumps across levels.
  • Validations (including custom ones) protect your data; callbacks do small automatic work.
  • Scopes name your queries and chain together; includes stops N+1.
  • Scoping lookups through Current.user keeps every level private to its owner.
  • A NULL finish 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)