Chuyển đến nội dung

Bài 8 · Routing and Controllers

Controllers and Actions

Learn how Rails controllers work: actions, instance variables, params, render, redirect_to, status codes, respond formats and the standard seven-action pattern, with runnable plain-Ruby stand-ins.

A controller is the traffic director of a Rails app. The router picks a controller and an action, and the action does three things: reads the request (mostly params), asks models for data, and decides what to send back, either a rendered page or a redirect. Good controllers are thin. They coordinate; the real business rules live in models.

This lesson covers the controller class, actions, instance variables that feed views, render and redirect_to, status codes and responding to different formats such as HTML and JSON. The real controller code is read-only on this page, and the stand-ins reproduce the behaviour in plain Ruby so you can run it.

A controller class

Ruby
# app/controllers/articles_controller.rb  (read-only)
class ArticlesController < ApplicationController
  def index
    @articles = Article.order(created_at: :desc)
  end

  def show
    @article = Article.find(params[:id])
  end
end

A controller is a class that inherits from ApplicationController, which in turn inherits from ActionController::Base. Each public method is an action. The name matches the route: articles#show calls show. Private methods are helpers and cannot be reached from the web, which is why you will see private in most controllers.

Instance variables set in an action (@article) are copied into the view, so the template can use them. If the action does not call render or redirect_to, Rails renders app/views/articles/show.html.erb for you. That is called the implicit render.

Reading the request

Inside an action you have several helpers:

Ruby
# read-only
params[:id]                 # path or query param, always a string
params[:article]            # a nested hash from a form
request.method              # "GET", "POST", ...
request.path                # "/articles/5"
request.headers["User-Agent"]
request.format              # :html, :json
cookies[:theme]             # see the sessions lesson
session[:user_id]

params merges three sources: path segments (/articles/:id), the query string (?page=2) and the request body (a submitted form or JSON). Because users control it, you must never trust it blindly; see strong parameters.

render and redirect_to

An action can end in only one of these (calling both raises AbstractController::DoubleRenderError).

Ruby
# read-only
render :edit                              # a different template for this controller
render "articles/show"                    # a template by path
render plain: "OK"                        # raw text
render json: @article                     # JSON
render status: :not_found                 # with HTTP status 404
render :new, status: :unprocessable_entity  # re-show a form with errors (422)

redirect_to @article                      # to /articles/5, 302 Found
redirect_to articles_path, notice: "Deleted"   # with a flash message
redirect_back fallback_location: root_path
head :no_content                          # status only, empty body

The difference matters: render shows a template now, in this same request. redirect_to tells the browser to make a new request to another URL. After a successful create, always redirect. Otherwise a browser refresh would resubmit the form and create a duplicate. This is the Post/Redirect/Get pattern.

sequenceDiagram
  participant B as Browser
  participant C as ArticlesController
  B->>C: POST /articles (form data)
  C-->>B: 302 redirect to /articles/7
  B->>C: GET /articles/7
  C-->>B: 200 HTML page

After a successful create, the redirect makes the final page a plain GET that is safe to refresh.

The standard actions

A typical resourceful controller looks like this (we use strong parameters, covered in the next lesson):

Ruby
# read-only
class ArticlesController < ApplicationController
  def index
    @articles = Article.all
  end

  def show
    @article = Article.find(params[:id])
  end

  def new
    @article = Article.new
  end

  def create
    @article = Article.new(article_params)
    if @article.save
      redirect_to @article, notice: "Created!"
    else
      render :new, status: :unprocessable_entity
    end
  end

  def edit
    @article = Article.find(params[:id])
  end

  def update
    @article = Article.find(params[:id])
    if @article.update(article_params)
      redirect_to @article
    else
      render :edit, status: :unprocessable_entity
    end
  end

  def destroy
    Article.find(params[:id]).destroy
    redirect_to articles_path, status: :see_other
  end

  private

  def article_params
    params.expect(article: [:title, :body])
  end
end

Study the create pattern: try to save; on success redirect, on failure re-render the form with status 422 so the browser shows the errors. The new and edit actions only prepare data for a form.

Status codes

Name (symbol) Code When
:ok 200 Normal success
:created 201 API: resource created
:no_content 204 Success, nothing to return
:found 302 Default redirect
:see_other 303 Redirect after DELETE/PATCH
:unprocessable_entity 422 Validation failed
:not_found 404 Record or page missing
:forbidden 403 Logged in but not allowed

Article.find raises ActiveRecord::RecordNotFound when the id does not exist, and Rails turns that into a 404 page in production automatically.

Stand-in: a controller with render and redirect

Our stand-in has a base class where render and redirect_to build a response, records live in a Hash, and a perform method plays the role of Rails dispatching an action. It enforces the "only one response" rule too.

Ruby Stand-in: actions, render, redirect_to and double render

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The show action sets @article and never calls render, so the base class renders the template named after the action. The create action shows the two exits. And broken triggers the double-render guard.

Responding to different formats

One action can answer in several formats. respond_to picks by the request's format (from the URL extension .json or the Accept header):

Ruby
# read-only
def show
  @article = Article.find(params[:id])
  respond_to do |format|
    format.html                              # renders show.html.erb
    format.json { render json: @article }
  end
end

If an action only needs one format, you can skip respond_to: Rails picks the template matching the format, so show.json.jbuilder is used for JSON requests automatically.

Stand-in: format negotiation

Ruby Stand-in: choosing a response format

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Keep actions short. If a controller action has more than about ten lines, move the logic into the model or a small plain Ruby object. Controllers should translate between HTTP and your domain, not hold the rules.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What happens if an action does not call render or redirect_to?

    Rails performs an implicit render of app/views/<controller>/<action>.html.erb.
  2. 2. Why redirect after a successful create?

    Post/Redirect/Get makes the resulting page a safe GET request.
  3. 3. Which status should you use when re-rendering a form with validation errors?

    422 tells the browser (and Turbo) that the submission failed validation.
  4. 4. What are the public methods of a controller called?

    Each public method is an action reachable through a route; private methods are not.

Summary

  • A controller is a class whose public methods are actions; instance variables pass data to views.
  • params merges path, query and body data and holds strings.
  • render shows a template in this request; redirect_to sends the browser to a new request. Use only one per action.
  • After a successful create, update or delete, redirect; on failure render the form with status 422.
  • respond_to lets one action answer in HTML, JSON and more; keep controllers thin.

Next: Strong Parameters and Filters

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.