Generating A Controller
suggest changeTo 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 the newly generated app/controllers/posts_controller.rb, you’ll see a controller with no actions:
class PostsController < ApplicationController
# empty
end
Pass action names to generate those methods:
$ rails g controller ControllerName method1 method2
To create a controller inside a module, pass the name as a path such as parent_module/controller_name (rails g controller admin/credit_cards). The next command is not namespaced. It generates CreditCardsController:
$ 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.