Rails provides a lot of generators, for controllers too of course.
You can generate a new controller by running this command in your app folder
rails generate controller NAME [action action] [options]
Note: You can also use rails g alias to invoke rails generate
For example, to generate a controller for a Product model, with #index and #show actions you would run
rails generate controller products index show
This will create the controller in app/controllers/products_controller.rb, with both the actions you specified
class ProductsController < ApplicationController
def index
end
def show
end
end
It will also create a products folder inside app/views/, containing the two templates for your controller's actions (i.e. index.html.erb and show.html.erb, note that the extension may vary according to your template engine, so if you're using slim, for example, generator will create index.html.slim and show.html.slim )
Furthermore, if you specified any actions they will also be added to your routes file
# config/routes.rb
get 'products/show'
get 'products/index'
Rails creates a helper file for you, in app/helpers/products_helper.rb, and also the assets files in app/assets/javascripts/products.js and app/assets/stylesheets/products.css. As for views, the generator changes this behaviour according to what's specified in your Gemfile: i.e., if you're using Coffeescript and Sass in your application, the controller generator will instead generator products.coffee and products.sass.
At last, but not least, Rails also generates test files for your controller, your helper and your views.
If you don't want any of these to be created for you can tell Rails to skip them, just prepend any option with
--no- or --skip, like this:
rails generate controller products index show --no-assets --no-helper
And the generator will skip both assets and helper
If you need to create a controller for a specific namespace add it in front of NAME:
rails generate controller admin/products
This will create your controller inside app/controllers/admin/products_controller.rb
Rails can also generate a complete RESTful controller for you:
rails generate scaffold_controller MODEL_NAME # available from Rails 4
rails generate scaffold_controller Product