Ruby on Rails / Controllers and Actions

Defining and Using Controllers in Rails

This tutorial will introduce you to the concept of controllers in Rails. We'll cover how to define and use controllers to handle various aspects of your application's logic.

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Covers how to create and manage controllers and actions in Rails.

Defining and Using Controllers in Rails

1. Introduction

In this tutorial, we will delve into the world of Rails controllers. Controllers are essential in Rails as they process incoming requests to your web application, interact with models, and render views to the user.

By the end of this guide, you will learn how to:

  • Define a controller in Rails
  • Implement actions in a controller
  • Use a controller to interact with models and views

This guide assumes that you have a basic understanding of Ruby and Rails.

2. Step-by-Step Guide

In Rails, a controller is simply a Ruby class which inherits from ApplicationController and follows the naming convention of CamelCase and ending with 'Controller'. Each public method in a controller is known as an 'action', and these actions are responsible for handling specific tasks.

2.1 Defining a Controller

To create a controller, you can use the rails generate controller command followed by the name of the controller. For instance, to create a PostsController, you can run:

rails generate controller Posts

This will create a new file at app/controllers/posts_controller.rb with the following content:

class PostsController < ApplicationController
end

2.2 Implementing Actions

Actions are defined as public methods within the controller. For instance, a show action can be defined as follows:

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

In this action, we're finding a post by its ID and storing it in an instance variable. This post can then be displayed to the user in a corresponding view.

2.3 Interacting with Models and Views

Controllers act as a bridge between models and views. They fetch data from the model and pass it to the view to be displayed.

For example, in the show action above, the @post instance variable can be used in the show view (app/views/posts/show.html.erb) to display the post:

<h1><%= @post.title %></h1>
<p><%= @post.content %></p>

3. Code Examples

Example - Posts Controller

Let's create a PostsController with index, show, new, edit, create, update, destroy actions:

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]

  # GET /posts
  def index
    @posts = Post.all
  end

  # GET /posts/1
  def show
  end

  # GET /posts/new
  def new
    @post = Post.new
  end

  # GET /posts/1/edit
  def edit
  end

  # POST /posts
  def create
    @post = Post.new(post_params)

    if @post.save
      redirect_to @post, notice: 'Post was successfully created.'
    else
      render :new
    end
  end

  # PATCH/PUT /posts/1
  def update
    if @post.update(post_params)
      redirect_to @post, notice: 'Post was successfully updated.'
    else
      render :edit
    end
  end

  # DELETE /posts/1
  def destroy
    @post.destroy
    redirect_to posts_url, notice: 'Post was successfully destroyed.'
  end

  private

  # Use callbacks to share common setup or constraints between actions.
  def set_post
    @post = Post.find(params[:id])
  end

  # Only allow a list of trusted parameters through.
  def post_params
    params.require(:post).permit(:title, :content)
  end
end

Each action in this controller corresponds to a specific task (displaying all posts, viewing a single post, creating a new post, etc.). The set_post method is a private method used to set the @post variable in several actions.

4. Summary

In this tutorial, we've learned how to define and use controllers in Rails. We've covered how to define a controller, implement actions, and use a controller to interact with models and views.

For further learning, try adding more actions to your controllers or exploring more complex use cases. You may also find the Rails Guides on controllers helpful.

5. Practice Exercises

  1. Create a UsersController with index, show, new, create, edit, and update actions.

  2. Add a before_action callback to the UsersController to set the @user variable in the show, edit, and update actions.

  3. Implement the create and update actions in the UsersController, including handling for when saving the user fails.

Remember, practice is key when learning a new concept. Don't be afraid to experiment and make mistakes - that's how you learn!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

Age Calculator

Calculate age from date of birth.

Use tool

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help