How to Use rails generate controller in Ruby on Rails
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.
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.
rails generate controller Posts index 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.
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 Part | Description |
|---|---|
| rails generate controller | Starts the controller generator |
| ControllerName | Name of the controller (capitalized, plural) |
| action1 action2 ... | List of actions (methods) to create inside the controller |
| --skip-routes | Option to skip adding routes automatically |
| --no-helper | Option to skip generating helper files |
| --no-assets | Option to skip generating JavaScript and CSS files |
Key Takeaways
rails generate controller ControllerName actions to create controllers with actions and related files.