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
.
This is just like the product show action:
class CategoriesController < ApplicationController
def show
@category = Category.find(params[:id])
end
end
Next, set up the category show page. You can base your code off the products index page and adjust it for categories.1
This is very similar to the products index page, but you're going through the @category.products
instead of @products
.
<h1><%= @category.name %></h1>
<ul>
<% @category.products.each do |product| %>
<li><%= link_to product.name, product %></b></li>
<% end %>
</ul>
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.