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

2026-11-18来源 dev.toEnglish

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

  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 

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:

  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 

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

原文:https://www.a8q9.cn/en/article/learn-rails-8-by-building-study-flow-part-4-associations-scopes-and-callbacks-bfae17.html

相关文章