Vinicius Fontoura
Vinicius Fontoura

Reputation: 163

How to group_by this array of hashs (Enumerable) [Ruby, Rails]

I have an array (@items) of hashs with this structure:

@items:

{'item' => item, 'stickers' => stickers}
...

And the item is an ActiveRecord with the attr I want to group_by: csgo_type.

My code:

<% @items.group_by { |d| d['item'][:csgo_type] }.each do |a| %>
    <%= render partial: 'item', locals: {a: a} %>
<% end %>

But this doesnt group at all.

I'm looking for a result like this:

[ { :csgo_type => #ActiveRecord(csgo_type 1), :items => [array of some @items of this type] }, {...} ...]

Upvotes: 3

Views: 466

Answers (1)

Vinicius Fontoura
Vinicius Fontoura

Reputation: 163

Solution:

<% @items.group_by { |d| d['item'].csgo_type }.each do |a,b| %>
    === <%= a.name %>
    <% b.each do |cada| %>
        <%= render partial: 'item', locals: {cada: cada, i: 1} %>
    <% end %>
<% end %>

Upvotes: 3

Related Questions