Ruby on Rails Generating A Controller


Example

To generate a controller (for example Posts), navigate to your project directory from a command line or terminal, and run:

$ rails generate controller Posts

You can shorten this code by replacing generate with g, for example:

$ rails g controller Posts

If you open up the newly generated app/controllers/posts_controller.rb you'll see a controller with no actions:

class PostsController < ApplicationController
    # empty
end

It's possible to create default methods for the controller by passing in controller name arguments.

$ rails g controller ControllerName method1 method2

To create a controller within a module, specify the controller name as a path like parent_module/controller_name. For example:

$ rails generate controller CreditCards open debit credit close
# OR
$ rails g controller CreditCards open debit credit close

This will generate the following files:

Controller: app/controllers/credit_cards_controller.rb
Test:       test/controllers/credit_cards_controller_test.rb
Views:      app/views/credit_cards/debit.html.erb [...etc]
Helper:     app/helpers/credit_cards_helper.rb

A controller is simply a class that is defined to inherit from ApplicationController.

It's inside this class that you'll define methods that will become the actions for this controller.