RoR Controllers Basics

Controllers are the traffic managers of your Rails application. They receive requests from the router, collect data from models, and send that data to views for display. Every action a user takes in your app — clicking a link, submitting a form, or deleting a record — gets handled by a controller action.

What a Controller Looks Like

app/controllers/articles_controller.rb

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
    else
      render :new
    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
    end
  end

  def destroy
    @article = Article.find(params[:id])
    @article.destroy
    redirect_to articles_path
  end

  private

  def article_params
    params.require(:article).permit(:title, :body)
  end

end

The Seven Standard Actions

Action    Purpose                         HTTP Verb + URL
-------------------------------------------------------------
index     Display all records             GET /articles
new       Show form to create             GET /articles/new
create    Save new record                 POST /articles
show      Display one record              GET /articles/:id
edit      Show form to edit               GET /articles/:id/edit
update    Save edited record              PATCH /articles/:id
destroy   Delete a record                 DELETE /articles/:id

Not every controller needs all seven. A read-only controller might only need index and show.

How a Controller Action Flows

User clicks "View Article" link
        |
        v
Router sends GET /articles/5 to ArticlesController#show
        |
        v
def show
  @article = Article.find(params[:id])   ← fetches article with ID=5
end
        |
        v
Rails looks for: app/views/articles/show.html.erb
        |
        v
Renders the view with @article available
        |
        v
Browser displays the article

The params Hash

params is a hash that holds all data sent with a request. It includes URL segments, query strings, and form data.

URL: /articles/7
params[:id]           = "7"

URL: /articles?page=2
params[:page]         = "2"

Form with title field:
params[:article][:title] = "My New Post"

Strong Parameters

Rails requires you to explicitly allow each field that comes from a form before saving it to the database. This protection prevents users from injecting unwanted data into your records.

private

def article_params
  params.require(:article).permit(:title, :body)
end
  • require(:article) — the form data must be nested under the key article
  • permit(:title, :body) — only these two fields are allowed through

Any field not listed in permit gets stripped out automatically, even if someone tries to send it.

Redirect vs Render

After a controller action runs, Rails either renders a view or redirects to another URL.

RENDER — Shows a view template directly
  render :new
  render :edit
  render "articles/show"

REDIRECT — Sends browser to a new URL (new HTTP request)
  redirect_to @article
  redirect_to articles_path
  redirect_to root_path

The key difference:

render   → No new request. Shows a view from this action's data.
redirect → Browser makes a brand new request to the given URL.

After a successful create or update, always redirect. After a failed save (validation errors), always render the form again so the user sees their errors.

Before Actions

before_action runs a method before one or more controller actions. Use it to avoid repeating the same code in multiple actions.

class ArticlesController < ApplicationController
  before_action :set_article, only: [:show, :edit, :update, :destroy]

  def show
    # @article is already set
  end

  def edit
    # @article is already set
  end

  private

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

Without before_action, you would write @article = Article.find(params[:id]) four times. The before action writes it once and shares it.

ApplicationController

All your controllers inherit from ApplicationController. Any method you put in ApplicationController becomes available in every controller in your app.

app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  before_action :require_login

  private

  def require_login
    redirect_to login_path unless current_user
  end
end

This pattern enforces login across your entire app from one place.

Flash Messages in Controllers

Flash messages pass one-time notices from a controller action to the next request. They disappear after being displayed once.

def create
  @article = Article.new(article_params)
  if @article.save
    flash[:notice] = "Article created successfully."
    redirect_to @article
  else
    flash[:alert] = "Could not save article. Please check the form."
    render :new
  end
end

In your view or layout, display flash messages like this:

<% flash.each do |type, message| %>
  <p><%= message %></p>
<% end %>

Controller Naming Convention

ResourceController FileClass Name
articlesarticles_controller.rbArticlesController
usersusers_controller.rbUsersController
order_itemsorder_items_controller.rbOrderItemsController

Controller names are always plural. Model names are always singular. This consistent naming is what lets Rails wire everything together without configuration.

Leave a Comment

Your email address will not be published. Required fields are marked *