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

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

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: 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
# 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.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

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: :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]

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 - 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_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"

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_action runs 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's study_plan_id, the lookup raises a 404. That's why study_plan_id is not in topic_params.
  • 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

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 raise RecordInvalid. 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: "m*@example.com", password: "secret123")
    @plan = user.study_plans.cr
Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.