Presenting Products

Premium Content - Free Preview

Now that our routes are all set up, let's set up the controller and views to display products.


Open up the products controller.

Part 1: In the index action. Add a line of code to assign all available products to a variable called @products.

The Code

Part 2:

Open up index.html.erb in products, and remove the boilerplate content that Rails generated. We have a @products variable available that contains a collection of the available products. If you were writing regular Ruby code, how would you print out the name of each product in @products?

(Review the coding challenge from Multiple Models before continuing on.)

You can loop through collections in the view with regular Ruby, you just need to specify which code to output. Here's how we can display each product in @products in embedded Ruby:


    <% @products.each do |product| %>
        <%= %>
    <% end %>

Note the <% tag at the beginning. The <% %> tag is used to run ruby code inside a template without outputting anything. In this case it's used to create a ruby each loop. The each loop will be used to iterate through each product.

The next line uses the <%= %> tag to output the name of each product. Instead of using print or puts, use these tags to display the output of a line of code. Always make sure to use <%= to display the output of a line of Ruby, and use <% for a line of ruby without output.

Part 3

If you add the above code to index.html.erb and reload /products', your products will be displayed, but they don't look very nice. Can you fix that with some HTML?

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]