Using rails 3.1, ruby 1.92. I have a bunch of products in a store: movies, music, and books. I have three scopes in my products controller, all called the same (movies, music, and books). The point of our assignment is to have the index of the product controller show all items on load of the site. No problem. We then have to link_to books, music, or movies, and have the appropriate products shown. Also done.
However, I now have three files in my views, and I need to make a partial to display all of these. I have used this:
<% @products.each do |product| %>
<div class="entry">
<%= image_tag(product.image_url) %>
<h3><%= product.title %></h3>
<%= sanitize(product.description) %>
<div class="price_line">
<span class="price"><%= number_to_currency(product.price) %></span>
<%= button_to 'Add to Cart', line_items_path(:product_id => product) %>
</div>
</div>
<% end %>
I don’t really understand what is happening. I have taken what is originally a ‘@product’ and with the use of my scope, it is now @book, or @music, etc. In my code with the three files, I have this code, but instead of ‘@products’ and ‘do |product|’, I have @books do |book| etc.
What do I need to do so the partial will be able to be functional using @books, @music, and @movies? Each time I pass these variables I get the NilClass error. How do I go about this?
Check out the rails guide on layouts and rendering – especially the section on partials, which I linked you directly to.
Basically, you want to refactor the code to avoid using @products, @books, @movies, etc, and make a partial that uses a local variable.
In your products view:
In your books view:
In your movies view:
And inside the partial, just change your
@products.each do |product|toproducts.each do |product|