Richlewis
Richlewis

Reputation: 15374

How to iterate through my array within a hash

Firstly, I am hoping my understanding is correct and I do in fact have a an array within my hash.

I've gotten so far but cant seem to iterate through each hash and its array. What I would like to do is have each tournament grouped by date (year only) and have all its tournaments listed underneath.

So far my logic is

Controller

@tournaments = Tournament.all
@tournament_year = @tournaments.group_by {|y| y.tourn_date.year}

View

<ul class="resp-tabs-list">
  <% @tournament_year.each do |y, t| %>
    <li><%= y %></li>
  <% end %>
</ul>

hash

{2014=>[#<Tournament id: 3, name: "WTS ", tourn_date: "2014-04-26", tourn_location: "Cardiff", created_at: "2014-04-26 14:57:21", updated_at: "2014-04-26 14:57:21">, #<Tournament id: 4, name: "CTS Nottingham", tourn_date: "2014-05-26", tourn_location: "Nottingham", created_at: "2014-04-26 14:57:39", updated_at: "2014-04-26 14:57:48">]}

My desired output would be below

<h3>2014</h3>
<ul>
  <li>Tournament Name 1</li>
  <li>Tournament Name 2</li>
</ul>

<h3>2013</h3>
<ul>
  <li>Tournament Name 1</li>
  <li>Tournament Name 2</li>
</ul>

Upvotes: 0

Views: 86

Answers (3)

xlembouras
xlembouras

Reputation: 8295

I would suggest

<% @tournament_year.each do |y, t| %>
  <h3> <%= y %></h3>
  <ul class="resp-tabs-list">
    <% t.each do |tournament| %>
      <li><%= "#{tournament.to_s}" %></li>
    <% end %>
  </ul>
<% end %>

where

#app/models/tournament.rb

def to_s
  "#{name} #{id}"
end

Upvotes: 1

Richlewis
Richlewis

Reputation: 15374

Ive just come up with this solution as an example, seems to work, can anyone see any reason why this would be incorrect?

<ul class="resp-tabs-list">
  <%= @tournament_year.each do |y, t| %>
    <li><%= y %></li>
      <%= @tournament_year[y].each do |x| %>
        <li><%= x.name %></li>
      <% end %>
  <% end %>
</ul>

Upvotes: 0

bjhaid
bjhaid

Reputation: 9752

Change your view as below:

<ul class="resp-tabs-list">
  <% @tournament_year.each do |y, t| %>
    <h3><%= y %></h3>
    <ul>
    <% t.each_with_index do |tournament, i| %>
      <li><%= tournament.name %> <%= i %></li>
    <% end %>
    </ul>
  <% end %>
</ul>

Upvotes: 2

Related Questions