开发者

How do I create a store catalog with rows and columns on index.html.erb in rails application

I have a store application and want my store items to display in a 3 column catalog. I want the 4th i开发者_Go百科tem to move to a new row automatically after the 3rd item is placed on the 3rd column on the first row. All items will be called from the database.

How can I acheive displaying my product catalog like thumbnails. At the moment this is what I have in my index.html.erb

<% @products.each do |product| %>
<table>
  <tr>
    <th>
<div class="entry">
  <div class="card-title" >
<%=h product.title %></div> <%= image_tag(product.image_url) %>

  <div class="price-line">
    <span class="price"><%= number_to_currency(product.price, :unit => "N", :format => "%u%n") %></span>
  </div>

  <% form_remote_tag :url => { :action => 'add_to_cart', :id => product } do %>
    <%= submit_tag "Add to Cart" , :class => "add_button" %>
    <% end %>

</div>

    </th>
</tr>
</table>
<% end %>

At the moment every item is shown in just one column but I want to display items like this:

Item A   Item B  Item C
Item D   Item E  Item F
Item G   ......  ......

Any help will be appreciated. I'm new to RoR.

Thanks. Ijespal


Rails has a nice helper for that: Array#in_groups_of

<table>
  <% @products.in_groups_of(3, false) do |row| %>
    <tr>
      <% row.each do |product| %>
        <td><%= product.name # and whatever else you want %></td>
      <% end %>
    </tr>
  <% end %>
</table>

The in_groups_of helper normally returns an array of arrays, which all have the size set by the first parameter. If the original number of elements are unable to fill the last array completely, then it is padded by nil values. If you pass false as a second argument, then the last array is left shorter than the others, without nil elements.


I'm not sure if this is the best way, but you can use something like

<table>
   <% @products.each_with_index do |product, index| %>

      <% if index%3==0 %>
         <tr>
      <% end %>

      <td><%= product.name%></td>

      <% if (index+1)%3==0 %>
         </tr>
      <% end %>

    <% end %>
</table>

Worked just fine here (:

Edit

It works, but edgerunner's answer is much better! :]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜