Displaying Categories


Premium Content - Free Preview

You saw how to create routes, and a controller and views to show products. Let's do something similar for categories.

Plan

Let's create a show page for categories so each category can be viewed at its own URL, such as categories/2. Each page should show all the products in that category as links.

Getting started

First, generate a categories controller with one action: show.

Next, remove the auto-generated category route in routes and replace it with a Rails resource like before:

resources :categories

In this case, we just want one route now, so modify it:

resources :categories, only: :show

This will only create the show route, and you can go to /rails/info/routes to see the new route. If you wanted to created additional category routes (without creating all of them), use an array. For example, this line would create show and index routes:

resources :categories, only: [:show, :index]

Creating the Show Page

Open up CategoriesController and set up the controller show action, so it gets the right category and assigns it to an instance variable @category.

The Code

Next, set up the category show page. You can base your code off the products index page and adjust it for categories.1

The Code

In the next page, we'll see how to clean up this code.

A Categories Column

Since your site isn't that large, it's not necessary to create a separate page to display all the categories on the site. Instead, you can add this information to the home page.


End of Free Content Preview. Please Sign in or Sign up to buy premium content.

Contact Us
Sign in or email us at [email protected]