我遇到了问题,需要一种简单的方法来对数组进行排序并在视图中使用它
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">]>
所以我尝试了类似的东西:
@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">]]]
在视图中:
<% @localfeeds.each do |f, t| %>
<p>city</p>
<%= f%>
<p>locality</p>
<% t.each do |y| %>
<%= y.locality%>
<%end%>
我们将不胜感激。
视图中的最终结果应为
City:
link to locality
link to locality
City:
link to locality
link to locality
工作,谢谢
答案 0 :(得分:1)
在group_by
函数之后,每个哈希值都是Localfeed实例,因此如果要打印每个位置值,请使用:
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