Generating a controller
suggest changeRails 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 (index.html.erb and show.html.erb). The extension follows the template engine. With Slim, the generator creates index.html.slim and show.html.slim.
If you specified any actions, they are also added to the routes file, in the order you listed them:
# config/routes.rb
get 'products/index'
get 'products/show'
These are individual get routes, not resources :products.
Rails creates a helper file in app/helpers/products_helper.rb, and asset files in app/assets/javascripts/products.js and app/assets/stylesheets/products.css. The generator follows the asset libraries in the app. With CoffeeScript and Sass, it generates products.coffee and products.scss (or products.sass, depending on the configured stylesheet engine).
Rails also generates test files for your controller, helper, and views.
If you don’t want any of these created, tell Rails to skip them. Prepend an 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, put 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