Onichan
Onichan

Reputation: 4526

Loop through items and place in correct list

I have a list of products which have two columns: Name and Category.

How can I loop through each product in @products and place them in list-groups with the same product.category?

Current Code:

This creates a new list-group for each product. I'd like to group the products with same categories together.

<% @products.each do |product| %>
    <div class="col-md-6 column_container">    
      <div class="list-group">
        <a class="list-group-item list-group-item-success active">
          <%= product.category %>
        </a>
        <a href="#" class="list-group-item">
          <%= product.name %>
        </a>
      </div>
    </div>
<% end %>

For example:

<div class="container">
  <div class="row">
    <div class="col-md-6 column_container">    
      <div class="list-group">
        <a class="list-group-item list-group-item-success active">
          Category Name                                 <---- category
        </a>
        <a href="#" class="list-group-item">
          Product1 Name                                 <---- has same category
        </a>
        <a href="#" class="list-group-item">
          Product1 Name                                 <---- has same category
        </a>
      </div>
    </div>

    <div class="col-md-6 column_container">    
      <div class="list-group">
        <a class="list-group-item list-group-item-success active">
          Category Name                                 <---- category
        </a>
        <a href="#" class="list-group-item">
          Product1 Name                                 <---- has same category
        </a>
        <a href="#" class="list-group-item">
          Product1 Name                                 <---- has same category
        </a>
      </div>
    </div>
  </div>
</div>

Should I be using two loops? One to loop through each category, then another nested loop to place each product?

Upvotes: 1

Views: 794

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54902

You can use group_by method:

<% @products.group_by(&:category).each do |category, products| %>
  # do something with category

  <% products.each do |product| %>
    # do something with each product
  <% end %>
<% end %>

You wanna sort the different categories by alphabetical order? Okay!

<% @products.group_by(&:category).sort_by{ |category, products| category.to_s }.each do |category, products| %>
  # ...
<% end %>

Upvotes: 4

Related Questions