Richardlonesteen
Richardlonesteen

Reputation: 594

Ruby sorting and displaying nested array

I got a problem, need a simple way to sort an array and use it in views

l = Localfeed.select(:id, :locality, :city)

 => #<ActiveRecord::Relation [#<Localfeed id: 94, city: "Cardiff", locality: "Splott">,
 #<Localfeed id: 95, city: "newport", locality: "allt-yr-yn">, #<Localfeed id: 29, city
: "Cardiff", locality: "splott">, #<Localfeed id: 30, city: "Cardiff", locality: "Adams
down">, #<Localfeed id: 31, city: "Cardiff", locality: "Cathays">]> 

so i tried something like:

@k = l.group_by {|k| k[:city] }
=> [["newport", [#<Localfeed id: 95, city: "newport", locality: "allt-yr-yn">]], ["Car
diff", [#<Localfeed id: 94, city: "Cardiff", locality: "Splott">, #<Localfeed id: 29, c
ity: "Cardiff", locality: "splott">, #<Localfeed id: 30, city: "Cardiff", locality: "Ad
amsdown">, #<Localfeed id: 31, city: "Cardiff", locality: "Cathays">]]] 

In the view:

          <% @localfeeds.each do |f, t| %>
          <p>city</p>
          <%= f%>
          <p>locality</p>
          <% t.each do |y| %>
          <%= y.locality%>
          <%end%>

Ideas would be appreciated.

End results in the views should be

City:
link to locality
link to locality
City:
link to locality
link to locality

WORKING, thank you

Upvotes: 0

Views: 73

Answers (1)

dddd1919
dddd1919

Reputation: 888

After group_by function, the value of each hash is a Localfeed instance, so if you want to print each locality value, use:

l = Localfeed.select(:id, :locality, :city)
k = l.group_by {|k| k[:city] }
k.each do |ct, lc|
  puts "#{ct}:"  ## print city
  lc.each {|l| puts "-- #{l.locality}"}  ## print locality in this city group
end

Upvotes: 1

Related Questions