我试图找出如何在我的视图中仅在轨道上的ruby中显示1个重复记录。
在我的控制器中我有
previous_three_days = Date.today - 3
@results = Result.where("fixture_date <= ?", previous_three_days)
@result_date = @results.group_by {|r| r.fixture_date}
在我看来,我有了这个
<% @result_date.sort.each do |date, results| %>
<%= date %>
<% results.each do |result| %>
<%= result.home_team %>
<%= result.home_score %> -
<%= result.away_score %>
<%= result.away_team %></span>
<% end %>
<% end %>
因此,虽然我正在通过fixture_date进行分组,但我希望确保home_team v away_team是唯一的,使用.uniq在这种情况下不起作用。
在这种情况下我的测试数据看起来像
19 Everton West Ham 2 0 2013-05-12 77 2013-05-16 11:18:18 2013-05-16 11:18:18
20 Everton West Ham 2 0 2013-05-12 80 2013-05-16 11:18:18 2013-05-16 11:18:18
21 Fulham Liverpool 1 3 2013-05-12 78 2013-05-16 11:18:18 2013-05-16 11:18:18
22 Fulham Liverpool 1 3 2013-05-12 81 2013-05-16 11:18:18 2013-05-16 11:18:18
23 Stoke Tottenham 1 2 2013-05-12 76 2013-05-16 11:18:18 2013-05-16 11:18:18
24 Stoke Tottenham 1 2 2013-05-12 79 2013-05-16 11:18:18 2013-05-16 11:18:18
并且视图中的输出是
Everton 2 - 0 West Ham
Everton 2 - 0 West Ham
Fulham 1 - 3 Liverpool
Fulham 1 - 3 Liverpool
Stoke 1 - 2 Tottenham
Stoke 1 - 2 Tottenham
这是有意义的,因为我正在通过fixture_date分组
任何帮助表示赞赏
答案 0 :(得分:3)
@results = Result.where("fixture_date <= ?", previous_three_days).group("home_team, away_team, fixture_date")
然后在视图中
<% @results.each do |result| %>
<%= result.home_team %>
<%= result.home_score %> -
<%= result.away_score %>
<%= result.away_team %></span>
<% end %>
答案 1 :(得分:1)
为什么数据库中有重复?也许你能解决这个问题?
如果没有,你可以使用独特的
results = results.uniq { |r| r.home_team }
上面发布的分组效果更好,因为它会更快更优雅