Skip to the workspace
Pebellslearn by building
Controllers  ›  Lesson

Creating Controllers and Actions

Controller Actions 15 minA controller is a class whose public methods are actions; each action ends by rendering a view (implicitly or explicitly) or by redirecting to another URL.

ruby on rails / Creating Controllers and Actions

Explore each scene at your own pace.

01 · The rule

The rule

Creating Controllers and Actions

The router has picked BooksController#index. Now Ruby code must run: fetch the books, choose what to send back. That code is a controller action, and every action ends in one of two ways.

The rule

Every action ends in a render or a redirect.

A controller is a class that inherits from ApplicationController. Its public methods are actions; private methods are helpers the router cannot reach.

bin/rails generate controller Books index show
class BooksController < ApplicationController
  def index
    @books = Book.order(:title)
  end                       # renders app/views/books/index.html.erb

  def show
    @book = Book.find(params[:id])
  end

  def create
    @book = Book.new(book_params)
    if @book.save
      redirect_to @book, notice: "Book added."
    else
      render :new, status: :unprocessable_entity
    end
  end
end

Render builds a response body now, from a template. If you do nothing, Rails renders the template named after the action, in the folder named after the controller: index → books/index.html.erb. This is implicit rendering. render :new picks another template in the same request, keeping all your instance variables.

Redirect sends a 302 with a new URL; the browser then makes a second request. redirect_to @book is shorthand for redirect_to book_path(@book). Instance variables do not survive a redirect, because it is a new request.

Other endings: render json: @book for APIs, and head :no_content for a response with no body.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.