0

I try to make the two columns list of products, this is my code

<table>
  <% ([email protected]).step(2) do |i| %>
    <tr><td><div id="product_left">
        <%= image_tag @products[i].photo.url(:small) %>
        <%= @products[i].name %><br/>
        Price: <%= @products[i].price %><br/>   
        <%= link_to "details", :action=>"show", :id=> @products[i].id %>
        &nbsp;&nbsp;
        <%= link_to "add to card", {:controller=> "carts", :action=>"add", :id=> @products[i].id}, :remote=> true %>
     </div> </td>
    <% if @products.length > i %>
     <td><div id="product_right">       
        <%= image_tag @products[i+1].photo.url(:small) %> 
        <%= @products[i+1].name %><br/>
        Price: <%= @products[i+1].price %><br/> 
        <%= link_to "details", :action=>"show", :id=> @products[i+1].id %>
        &nbsp;&nbsp;
        <%= link_to "add to card", {:controller=> "carts", :action=>"add", :id=> @products[i+1].id}, :remote=> true %>
     </div></td> 
     <% end %>
   </tr>
  <% end %>
  </table>

the problem is in the second div, rails give me an error on @products[i+1]. How can I solve it?

2
  • undefined method `photo' for nil:NilClass it seems like the second element is nil but I have the second element in @products array, if I delete the second div it displays me all elements in array with step 2 Commented May 18, 2011 at 15:45
  • That is what you should write in your question Commented May 18, 2011 at 15:49

1 Answer 1

1
<table>
  <% @products.each_slice(2) do |products| -%>
    <tr>
      <% products.zip(["left", "right"]).each do |product, side| -%>
        <td>
          <div id="product_<%= side %>">
            <%= image_tag product.photo.url(:small) %>
            <%= product.name %><br/>
            Price: <%= product.price %><br/>   
            <%= link_to "details", product %>
            &nbsp;&nbsp;
            <%= link_to "add to card", [:add, :carts, product], :remote=> true %>
          </div> 
        </td>
      <% end %>
    </tr>
  <% end -%>
</table>

Also you shouldn't use not uniq id. Here you have got multiple product_left and product_right ids. That's not good

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.