Skip to content

Ror Controllers

DodaTech 4 min read

title: Ruby on Rails Controllers — Complete Guide to Request Handling description: 'Learn Ruby on Rails controllers: actions, parameters, filters, session management, flash messages, responds_to, and strong parameters for secure request handling.' date: 2026-06-28 lastmod: 2026-06-28 weight: 15 tags: [backend, ror]


Ruby on Rails controllers handle HTTP requests, process parameters, interact with models, manage sessions, and return responses as HTML, JSON, or other formats.

## What You'll Learn

By the end of this tutorial, you'll implement controller actions with CRUD, use before_action filters, manage sessions and cookies, handle multiple response formats, and secure parameters.

## Real-World Use

A ProductsController handles index (list), show (detail), create (add), update (edit), and destroy (delete). Filters check authentication before every action except index and show.

## Controllers Learning Path

```mermaid
flowchart LR
  A[Routing] --> B[Controllers]
  B --> C[Views]
  C --> D[Models]
  D --> E[Active Record]
  B --> F{You Are Here}
  style F fill:#f90,color:#fff

Controller with Actions

class PostsController < ApplicationController
  before_action :authenticate_user!, except: [:index, :show]
  before_action :set_post, only: [:show, :edit, :update, :destroy]

  def index
    @posts = Post.published.recent
  end

  def show
  end

  def new
    @post = Post.new
  end

  def create
    @post = current_user.posts.build(post_params)
    if @post.save
      redirect_to @post, notice: "Post created."
    else
      render :new, status: :unprocessable_entity
    end
  end

  def edit
  end

  def update
    if @post.update(post_params)
      redirect_to @post, notice: "Post updated."
    else
      render :edit, status: :unprocessable_entity
    end
  end

  def destroy
    @post.destroy
    redirect_to posts_path, notice: "Post deleted."
  end

  private

  def set_post
    @post = Post.find(params[:id])
  end

  def post_params
    params.require(:post).permit(:title, :body, :published)
  end
end

Filters

class ApplicationController < ActionController::Base
  before_action :set_locale
  before_action :track_page_view

  after_action :log_request

  around_action :measure_execution_time

  private

  def set_locale
    I18n.locale = params[:locale] || I18n.default_locale
  end

  def track_page_view
    # ...
  end

  def log_request
    Rails.logger.info "#{request.method} #{request.path} - #{response.status}"
  end

  def measure_execution_time
    start = Time.current
    yield
    elapsed = Time.current - start
    Rails.logger.debug "Request took #{elapsed.round(3)}s"
  end
end

Sessions and Flash

class SessionsController < ApplicationController
  def create
    user = User.find_by(email: params[:email])
    if user&.authenticate(params[:password])
      session[:user_id] = user.id
      redirect_to root_path, notice: "Signed in successfully"
    else
      flash.now[:alert] = "Invalid email or password"
      render :new, status: :unprocessable_entity
    end
  end

  def destroy
    session[:user_id] = nil
    redirect_to root_path, notice: "Signed out"
  end
end

Responding with Different Formats

class PostsController < ApplicationController
  def index
    @posts = Post.recent
    respond_to do |format|
      format.html
      format.json { render json: @posts }
      format.xml  { render xml: @posts }
      format.csv  { send_data @posts.to_csv, filename: "posts.csv" }
    end
  end
end

Common Mistakes

1. Fat Controllers

Controllers with hundreds of lines violate single responsibility. Move business logic to models or service objects.

2. Not Using before_action

Duplicating @post = Post.find(params[:id]) in every action violates DRY. Use before_action :set_post.

3. Forgetting Strong Parameters

Without params.require.permit, mass assignment vulnerabilities exist. Always whitelist parameters.

4. Using redirect_to After Failed Save

If save fails, use render to show errors. redirect_to loses the form data and error messages.

5. Not Handling Authentication Properly

Check before_action :authenticate_user! on controllers that need login. Skip for public pages only.

Practice Questions

1. What is a before_action filter?

A method that runs before specified controller actions. Used for authentication, finding records, setting variables.

2. What is strong parameters?

params.require(:model).permit(:attr1, :attr2) whitelists allowed parameters, preventing mass assignment attacks.

3. How do you redirect with a success message?

redirect_to @post, notice: "Success" sets flash[:notice] automatically.

4. What is the difference between render and redirect_to?

render renders a template (stays on same URL). redirect_to sends a new HTTP request to a different URL.

5. Challenge: Create a controller with CRUD actions, before_action filters, and strong parameters.

class ArticlesController < ApplicationController
  before_action :set_article, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, except: [:index, :show]

  def index
    @articles = Article.all
  end

  def show; end

  def new
    @article = Article.new
  end

  def create
    @article = current_user.articles.build(article_params)
    if @article.save
      redirect_to @article, notice: "Article created"
    else
      render :new, status: :unprocessable_entity
    end
  end

  private

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

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

FAQ

What is ApplicationController?

The base controller all other controllers inherit from. Add shared logic like authentication, locale setting, or error handling here.

How do I handle 404 errors in controllers?

Use rescue_from ActiveRecord::RecordNotFound, with: :not_found in ApplicationController.

What is the flash hash?

A hash that persists data for one request. flash[:notice] for success, flash[:alert] for errors.

Can controllers respond to multiple formats?

Yes. Use respond_to do |format| with format.html, format.json, format.xml blocks.

What are cookies in Rails?

cookies.permanent[:key] = value stores data in the browser. Used for remember-me tokens.

Mini Project: Articles Controller

Create a complete CRUD controller for articles with authentication and filters.

class ArticlesController < ApplicationController
  before_action :authenticate_user!, except: [:index, :show]
  before_action :set_article, only: [:show, :edit, :update, :destroy]

  def index
    @articles = Article.includes(:user).recent
  end

  def show; end

  def new
    @article = Article.new
  end

  def create
    @article = current_user.articles.build(article_params)
    if @article.save
      redirect_to @article
    else
      render :new, status: :unprocessable_entity
    end
  end

  private

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

What's Next

Ruby on Rails Views Ruby on Rails Models

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro