0
0
RailsHow-ToBeginner · 3 min read

How to Create Controller in Rails: Simple Steps and Example

In Rails, you create a controller using the rails generate controller ControllerName command, which sets up a new controller file and related views. This command creates a class inheriting from ApplicationController where you define actions as methods to handle web requests.
📐

Syntax

The basic syntax to create a controller in Rails is:

rails generate controller ControllerName action1 action2 ...

Here, ControllerName is the name of your controller (usually plural and capitalized), and action1, action2, etc. are the names of methods (actions) you want to add inside the controller.

This command creates a controller file in app/controllers, view folders for each action, and updates routes if needed.

bash
rails generate controller Articles index show new create
💻

Example

This example creates a controller named PostsController with two actions: index and show. The controller handles requests to list posts and show a single post.

ruby
class PostsController < ApplicationController
  def index
    @posts = Post.all
  end

  def show
    @post = Post.find(params[:id])
  end
end
Output
<p>When visiting <code>/posts</code>, Rails runs the <code>index</code> action showing all posts.<br>Visiting <code>/posts/1</code> runs the <code>show</code> action showing the post with ID 1.</p>
⚠️

Common Pitfalls

  • Wrong controller name: Controller names must be plural and capitalized (e.g., PostsController), or Rails won't find them.
  • Missing actions: Forgetting to define an action method causes routing errors.
  • Not restarting server: After creating a controller, restart the Rails server to load changes.
  • Incorrect routes: Ensure routes are set up for your controller actions in config/routes.rb.
bash
## Wrong way (singular controller name)
rails generate controller Post index

## Right way (plural controller name)
rails generate controller Posts index
📊

Quick Reference

Here is a quick summary of the controller creation process in Rails:

StepCommand / Description
Create controllerrails generate controller ControllerName action1 action2
Define actionsAdd methods inside the controller class for each action
Set routesAdd routes in config/routes.rb if needed
Restart serverRestart Rails server to apply changes
Access actionsVisit URLs matching routes to trigger controller actions

Key Takeaways

Use the command 'rails generate controller ControllerName actions' to create a controller with actions.
Controller names should be plural and capitalized to follow Rails conventions.
Define each action as a method inside the controller class inheriting from ApplicationController.
Ensure routes are properly set up to connect URLs to controller actions.
Restart the Rails server after creating or modifying controllers to see changes.