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
Simply call your Product class method
available to get all the available products:
class ProductsController < ApplicationController #... def index @products = Product.available end end
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
(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| %> <%= product.name %> <% end %>
<% 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
The next line uses the
<%= %> tag to output the name of each product. Instead of using
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.
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?