DEV Community

Cover image for Learn Rails 8 by Building Study Flow, Part 3: Routes, Controllers and Your First CRUD
Shrouk Abozeid
Shrouk Abozeid

Posted on AI-assisted

Learn Rails 8 by Building Study Flow, Part 3: Routes, Controllers and Your First CRUD

In Part 2 users could sign up and log in. But the dashboard is empty. Time to build the first real feature: study plans, such as "Learn SQL" or "Prepare for the AWS exam".

This is where you'll meet the pattern behind most Rails apps: CRUD (Create, Read, Update, Delete), done the Rails way.

What you'll learn

  • How resources turns one line into seven routes
  • Generating a model and a migration
  • belongs_to / has_many associations and validations
  • Writing a CRUD controller and a form with form_with
  • The difference between redirect_to and render
  • How to make sure users only see their own data

Step 1: Routes: one line, seven URLs

Open config/routes.rb and add:

Rails.application.routes.draw do
  resources :study_plans
  root "dashboard#show"

  resource :session
  resources :passwords, param: :token
  resource :registration, only: %i[new create]

  get "up" => "rails/health#show", as: :rails_health_check
end
Enter fullscreen mode Exit fullscreen mode

Then see what it produced:

bin/rails routes -g study_plan
Enter fullscreen mode Exit fullscreen mode
study_plans      GET     /study_plans          study_plans#index
                 POST    /study_plans          study_plans#create
new_study_plan   GET     /study_plans/new      study_plans#new
edit_study_plan  GET     /study_plans/:id/edit study_plans#edit
study_plan       GET     /study_plans/:id      study_plans#show
                 PATCH   /study_plans/:id      study_plans#update
                 DELETE  /study_plans/:id      study_plans#destroy
Enter fullscreen mode Exit fullscreen mode

That's REST: the URL names the thing (a study plan), and the HTTP verb says what to do with it.

Action Verb + URL Purpose
index GET /study_plans list all
show GET /study_plans/:id show one
new GET /study_plans/new form for a new one
create POST /study_plans save the new one
edit GET /study_plans/:id/edit form to change one
update PATCH /study_plans/:id save the change
destroy DELETE /study_plans/:id delete one

Each route gets a name that becomes two helpers: study_plans_path (/study_plans) and study_plans_url (the full address). You'll use them everywhere instead of typing URLs.

We'll implement new, create, edit, update and destroy now. index and show come later, because our dashboard will list plans instead of a separate index page, and show arrives in Part 4.

Plural vs singular: resources vs resource

In Part 2 we wrote resource :session (singular). Here we wrote resources :study_plans (plural). The difference:

  • resources: many of them, so URLs carry an :id.
  • resource: just one, so there's no :id. "Your session" and "your registration" are unambiguous.

Step 2: The model and migration

bin/rails generate model StudyPlan name:string description:text daily_hour:integer user:references
Enter fullscreen mode Exit fullscreen mode

Open the migration it created and add null: false to name:

class CreateStudyPlans < ActiveRecord::Migration[8.1]
  def change
    create_table :study_plans do |t|
      t.string :name, null: false
      t.text :description
      t.integer :daily_hour
      t.references :user, null: false, foreign_key: true

      t.timestamps
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

Then run it:

bin/rails db:migrate
Enter fullscreen mode Exit fullscreen mode

What each line does:

  • A migration is a versioned, reversible change to the database. Everyone who runs the app gets the same schema.
  • user:references adds a user_id column, an index, and a foreign key, so the database itself refuses a plan that points to a user who doesn't exist.
  • null: false makes the database enforce that a name exists. We'll also check this in Ruby, because the database error is ugly for users.

Check db/schema.rb. Rails updated it for you.

Step 3: Associations and validations

# app/models/study_plan.rb
class StudyPlan < ApplicationRecord
  belongs_to :user

  validates :name, presence: true
end
Enter fullscreen mode Exit fullscreen mode
# app/models/user.rb  (add one line)
has_many :study_plans, dependent: :destroy
Enter fullscreen mode Exit fullscreen mode
  • belongs_to :user and has_many :study_plans are the two sides of one relationship. They give you plan.user and user.study_plans.
  • dependent: :destroy means deleting a user deletes their plans too.
  • validates :name, presence: true blocks saving a plan without a name, and records an error message you can show to the user.

Try it in the console:

user = User.first
plan = user.study_plans.create(name: "Learn SQL", daily_hour: 2)
plan.persisted?        # => true
bad = user.study_plans.build(description: "no name")
bad.save               # => false
bad.errors.full_messages
# => ["Name can't be blank"]
Enter fullscreen mode Exit fullscreen mode

build creates an object without saving, and create builds and saves. Both automatically set user_id because we went through the association. Remember this, because it's the key to the next step.

Step 4: The controller, with security built in

# app/controllers/study_plans_controller.rb
class StudyPlansController < ApplicationController
  def new
    @study_plan = Current.user.study_plans.build
  end

  def create
    @study_plan = Current.user.study_plans.build(study_plan_params)
    if @study_plan.save
      redirect_to root_path, notice: "Study plan created successfully."
    else
      render :new, status: :unprocessable_content
    end
  end

  def edit
    @study_plan = Current.user.study_plans.find(params[:id])
  end

  def update
    @study_plan = Current.user.study_plans.find(params[:id])
    if @study_plan.update(study_plan_params)
      redirect_to root_path, notice: "Study plan updated successfully."
    else
      render :edit, status: :unprocessable_content
    end
  end

  def destroy
    @study_plan = Current.user.study_plans.find(params[:id])
    @study_plan.destroy
    redirect_to root_path, notice: "Study plan deleted successfully."
  end

  private

  def study_plan_params
    params.expect(study_plan: [ :name, :description, :daily_hour ])
  end
end
Enter fullscreen mode Exit fullscreen mode

Four ideas to take from this:

1. Look up records through the current user

Look at Current.user.study_plans.find(params[:id]). We don't write StudyPlan.find(params[:id]).

Why? Imagine plan 7 belongs to Sara, and Omar changes the URL to /study_plans/7/edit. With StudyPlan.find(7), Omar would edit Sara's plan. With Current.user.study_plans.find(7), Rails only searches Omar's plans, finds nothing, and responds with a 404. One habit, and a whole class of security bugs (called IDOR) disappears. Use it everywhere.

2. build through the association

Current.user.study_plans.build(...) sets user_id for us. A user can never create a plan for someone else, and we don't have to permit user_id as a parameter.

3. redirect_to vs render

  • On success, we redirect_to. The browser makes a new request, and refreshing the page won't resubmit the form. This is the Post/Redirect/Get pattern.
  • On failure, we render the form again, because we want to keep what the user typed and show errors. The status: :unprocessable_content (422) tells Turbo that the form was rejected. Without it, Turbo ignores the response and the user sees nothing happen.

4. params.expect again

As in Part 2, expect demands a study_plan hash and permits only these three fields. Any extra field sent by an attacker is dropped.

Step 5: The form

app/views/study_plans/new.html.erb:

<h1 class="font-bold text-4xl">Create Study Plan</h1>

<% if @study_plan.errors.any? %>
  <div class="py-2 px-3 bg-red-50 mb-5 text-red-500 rounded-lg">
    <%= @study_plan.errors.full_messages.to_sentence %>
  </div>
<% end %>

<%= form_with model: @study_plan do |form| %>
  <%= form.text_field :name, required: true, autofocus: true, placeholder: "Enter study plan name" %>
  <%= form.text_field :description, placeholder: "Enter study plan description" %>
  <%= form.number_field :daily_hour, placeholder: "Enter daily hours" %>
  <%= form.submit "Create Study Plan" %>
<% end %>

<%= link_to "Back to Dashboard", root_path %>
Enter fullscreen mode Exit fullscreen mode

edit.html.erb is the same form with the heading "Update Study Plan" and the button "Update Study Plan". (You'll notice the two views are nearly identical. Extracting them into a shared _form partial is a great exercise. We'll practice partials properly in Part 5.)

The magic is in form_with model: @study_plan. Rails looks at the object and decides everything:

  • New record → POST /study_plans (hits create)
  • Saved record → PATCH /study_plans/7 (hits update)
  • It also names the fields study_plan[name], which is why params.expect(study_plan: [...]) matches.

Step 6: Show plans on the dashboard

# app/controllers/dashboard_controller.rb
class DashboardController < ApplicationController
  def show
    @study_plans = Current.user.study_plans
  end
end
Enter fullscreen mode Exit fullscreen mode
<%# app/views/dashboard/show.html.erb %>
<h1 class="font-bold text-4xl">Dashboard</h1>
<%= button_to "Log out", session_path, method: :delete %>

<% if @study_plans.any? %>
  <h2 class="font-bold text-2xl mt-6">Your Study Plans</h2>
  <ul class="mt-4">
    <% @study_plans.each do |plan| %>
      <li class="mb-2">
        <strong><%= plan.name %></strong> - <%= plan.description %>
        (Daily Hours: <%= plan.daily_hour %>)
        <%= link_to "Edit", edit_study_plan_path(plan) %>
        <%= link_to "Delete", study_plan_path(plan),
              data: { turbo_method: :delete, turbo_confirm: "Are you sure?" } %>
      </li>
    <% end %>
  </ul>
<% else %>
  <p class="text-gray-500">You have no study plans yet.</p>
<% end %>

<%= link_to "Create a Study Plan", new_study_plan_path %>
Enter fullscreen mode Exit fullscreen mode

A few details:

  • edit_study_plan_path(plan) is built from the route name edit_study_plan. Pass the record and Rails extracts the id.
  • <%= plan.name %> escapes HTML automatically, so a plan named <script>... won't run code.
  • A link normally makes a GET request, so for deleting we add data: { turbo_method: :delete }. turbo_confirm pops up an "Are you sure?" dialog before sending.

Run bin/dev and try the whole loop: create, edit, delete a plan. Then sign up a second user in a private browser window, and notice they don't see the first user's plans.

✅ How to test this

Manual security check. Create a plan as user A and note its id in the URL (for example /study_plans/3/edit). Log in as user B and visit that URL. You should get a 404 page, not an edit form.

Automated tests. Create test/models/study_plan_test.rb:

require "test_helper"

class StudyPlanTest < ActiveSupport::TestCase
  setup do
    @user = User.create!(email_address: "me@example.com", password: "secret123")
  end

  test "is valid with a name" do
    assert @user.study_plans.build(name: "Learn SQL").valid?
  end

  test "requires a name" do
    plan = @user.study_plans.build(name: "")

    assert_not plan.valid?
    assert_includes plan.errors[:name], "can't be blank"
  end

  test "is deleted with its user" do
    @user.study_plans.create!(name: "Learn SQL")

    assert_difference("StudyPlan.count", -1) { @user.destroy }
  end
end
Enter fullscreen mode Exit fullscreen mode

And test/controllers/study_plans_controller_test.rb:

require "test_helper"

class StudyPlansControllerTest < 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")

    post session_path, params: { email_address: "me@example.com", password: "secret123" }
  end

  test "creates a plan owned by the current user" do
    assert_difference -> { @user.study_plans.count }, 1 do
      post study_plans_path, params: { study_plan: { name: "Learn Rails", daily_hour: 2 } }
    end

    assert_redirected_to root_path
  end

  test "re-renders the form when invalid" do
    assert_no_difference("StudyPlan.count") do
      post study_plans_path, params: { study_plan: { name: "" } }
    end

    assert_response :unprocessable_content
  end

  test "ignores a user_id sent by the client" do
    post study_plans_path, params: { study_plan: { name: "Sneaky", user_id: @other.id } }

    assert_equal @user, StudyPlan.find_by!(name: "Sneaky").user
  end

  test "updates a plan" do
    patch study_plan_path(@plan), params: { study_plan: { name: "Learn PostgreSQL" } }

    assert_equal "Learn PostgreSQL", @plan.reload.name
  end

  test "deletes a plan" do
    assert_difference("StudyPlan.count", -1) { delete study_plan_path(@plan) }
  end

  test "cannot edit, update or delete another user's plan" do
    get edit_study_plan_path(@others_plan)
    assert_response :not_found

    patch study_plan_path(@others_plan), params: { study_plan: { name: "Hacked" } }
    assert_response :not_found
    assert_equal "Not yours", @others_plan.reload.name

    assert_no_difference("StudyPlan.count") { delete study_plan_path(@others_plan) }
    assert_response :not_found
  end

  test "dashboard lists only my plans" do
    get root_path

    assert_select "strong", "Learn SQL"
    assert_select "strong", text: "Not yours", count: 0
  end
end
Enter fullscreen mode Exit fullscreen mode
bin/rails test
Enter fullscreen mode Exit fullscreen mode

The "another user's plan" test is the most valuable one in the file. It proves the 404 behavior from Step 4, and it will protect you if someone later "simplifies" a lookup to StudyPlan.find.

Common mistakes

  • Typing StudyPlan.find(params[:id]) in a controller. It works, and it's a security hole. Always start from Current.user.
  • Form fails and nothing happens. You rendered without status: :unprocessable_content. Turbo ignores a 200 response to a form submission.
  • ActionController::ParameterMissing / 400. The field names don't match params.expect(study_plan: ...). Check you used form_with model:, not a bare URL.
  • "Delete" opens a 404 or does nothing. Links send GET. Add data: { turbo_method: :delete } or use button_to.
  • Forgetting bin/rails db:migrate after generating the model gives PG::UndefinedTable.

Recap

  • resources maps URLs and HTTP verbs to seven controller actions; bin/rails routes shows the result.
  • A migration changes the database; a model validates and relates records.
  • form_with model: builds the right form for a new or existing record.
  • Success → redirect_to; failure → render with a 422 status.
  • Always load records through the current user, so people can only reach their own data.

Next up

A study plan isn't very useful empty. In Part 4 we'll add topics and study sessions inside plans and learn how associations, scopes and has_many :through let us ask questions like "which sessions are running right now?"

Top comments (0)