0

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

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.