我尝试将两列产品列表制作成产品列表,这是我的代码
<table>
<% (0..@products.length-1).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 %>
<%= 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 %>
<%= link_to "add to card", {:controller=> "carts", :action=>"add", :id=> @products[i+1].id}, :remote=> true %>
</div></td>
<% end %>
</tr>
<% end %>
</table>
问题出在第二个div中,Rails 在 @products[I+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 %>
<%= link_to "add to card", [:add, :carts, product], :remote=> true %>
</div>
</td>
<% end %>
</tr>
<% end -%>
</table>
此外,您不应该使用unq id
。在这里,您有多个product_left
和product_right
ID。那不好