0
0
Ruby on Railsframework~5 mins

Controller generation in Ruby on Rails

Choose your learning style9 modes available
Introduction

A controller in Rails helps manage how your app responds to user actions. Generating a controller creates the files you need to handle web requests easily.

When you want to add a new page or feature to your Rails app.
When you need to organize how your app handles different user actions.
When you want to quickly create a controller with some default actions.
When starting a new resource to manage data like articles or users.
Syntax
Ruby on Rails
rails generate controller ControllerName action1 action2 ...
Replace ControllerName with the name of your controller, usually plural and capitalized.
List any actions (methods) you want to create inside the controller after the name.
Examples
This creates a WelcomeController with an index action and related view files.
Ruby on Rails
rails generate controller Welcome index
This creates an ArticlesController with show, edit, and update actions.
Ruby on Rails
rails generate controller Articles show edit update
This creates a UsersController with no actions yet. You can add actions later.
Ruby on Rails
rails generate controller Users
Sample Program

This example shows how to generate a controller named BooksController with two actions: index and show. Rails creates the controller file and empty methods for these actions. It also creates view files where you can add HTML to display content.

Ruby on Rails
# Run this command in terminal:
rails generate controller Books index show

# This creates a BooksController with two actions: index and show.

# app/controllers/books_controller.rb
class BooksController < ApplicationController
  def index
    # code to list books
  end

  def show
    # code to show a single book
  end
end

# app/views/books/index.html.erb and show.html.erb are also created for views.
OutputSuccess
Important Notes

Controllers generated this way come with empty action methods you can fill with your code.

Rails also creates matching view files for each action automatically.

You can always add or remove actions later by editing the controller file.

Summary

Use rails generate controller to quickly create a controller and its actions.

Controllers handle user requests and decide what to show or do next.

Rails creates helpful files for you to start building your app's pages.