Defining and Using Controllers in Rails

Tutorial 1 of 5

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!