0
0
RailsHow-ToBeginner · 3 min read

How to Use rails generate controller in Ruby on Rails

Use rails generate controller ControllerName action1 action2 to create a new controller with specified actions in Ruby on Rails. This command creates controller files, views, routes, and test files automatically.
📐

Syntax

The basic syntax for generating a controller in Rails is:

  • rails generate controller ControllerName action1 action2 ...

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

bash
rails generate controller ControllerName action1 action2
💻

Example

This example creates a PostsController with two actions: index and show. It also generates views for these actions, a helper file, a test file, and updates routes.

bash
rails generate controller Posts index show
Output
Running via Spring preloader in process 12345 create app/controllers/posts_controller.rb invoke erb create app/views/posts create app/views/posts/index.html.erb create app/views/posts/show.html.erb invoke test_unit create test/controllers/posts_controller_test.rb invoke helper create app/helpers/posts_helper.rb invoke test_unit create test/helpers/posts_helper_test.rb invoke assets invoke coffee create app/assets/javascripts/posts.coffee invoke scss create app/assets/stylesheets/posts.scss route get 'posts/index' route get 'posts/show'
⚠️

Common Pitfalls

1. Naming conventions: Controller names should be plural and capitalized (e.g., PostsController), but when generating, use the plural form without "Controller" (e.g., Posts).

2. Forgetting to add actions: If you don't specify actions, the controller will be created empty without views or routes.

3. Routes not updating: The generator adds routes only for the actions you specify; if you add new actions later, you must update routes manually.

bash
Wrong:
rails generate controller posts

Right:
rails generate controller Posts index show
📊

Quick Reference

Here is a quick summary of the rails generate controller command:

Command PartDescription
rails generate controllerStarts the controller generator
ControllerNameName of the controller (capitalized, plural)
action1 action2 ...List of actions (methods) to create inside the controller
--skip-routesOption to skip adding routes automatically
--no-helperOption to skip generating helper files
--no-assetsOption to skip generating JavaScript and CSS files

Key Takeaways

Use rails generate controller ControllerName actions to create controllers with actions and related files.
Controller names should be capitalized and plural, but specify only the name without 'Controller' in the command.
Specify actions to generate views and routes automatically; otherwise, you get an empty controller.
Check generated routes and add new ones manually if you add actions later.
Use options like --skip-routes or --no-assets to customize what files are created.