Premium Content - Free Preview
We displayed the name of one product on our home page, but to let people browse our store, we need to create two new pages:
- a page to view all products
- a page to view all the information about one product
To get an idea of the page you want, you can first create a mockup of the page with either a pen and paper or a simple online tool, such as moqups.com. Here's a really simple picture showing a page to view a list of products:
Once you figured out what pages you want, it's time to implement it in Rails. Since we're creating a completely new group of pages, the first step is to create a new controller. We're going to display products, so let's call our controller ProductsController.
What name should we give to the two pages above? Rails actually has standard names for this purpose. index is used to display a list of the items, while show is used to show one item. Run the following command in the terminal to create a controller for those 2 pages:
rails generate controller Products show index
Previously we created custom routes individually, but Rails provides standard shortcuts to create common URL patterns. Currently, we want to create
index pages for products, but these kinds of pages could be used for other models also, such as Categories or Users. Since pages like
index appear so often, Rails provides a standard
resources way for creating their routes.
A resource is an item which has standard URLs for performing standard CRUD operations. Rails lets us declare these standard URLs in the routes file with the keyword
resources. Before we do this, let's check what routes currently exist in our application.