Controllers & Actions
Now that we’ve defined routes for Products, let’s implement the controller and actions to handle requests to these URLs.
This command will generate a ProductsController
with an index action. Since
we’ve already set up routes, we can skip that part of the generator using a
flag.
$ bin/rails generate controller Products index --skip-routes
This command generates a handful of files for our controller:
- The controller itself
- A views folder for the controller we generated
- A view file for the action we specified when generating the controller
- A test file for this controller
- A helper file for extracting logic in our views
Let’s take a look at the ProductsController defined in . It should look like this:
class ProductsController < ApplicationController def index endend
The index
method here is an Action. Even though it’s an empty method, Rails
will default to rendering a template with the matching name.
The index
action will render . If we open
up that file in our code editor, we’ll see the HTML it renders.
<h1>Products#index</h1><p>Find me in app/views/products/index.html.erb</p>
Files
Preparing Environment
- Preparing Ruby runtime
- Prepare development database