0

I am trying to find out how to only display 1 of duplicated records in ruby on rails in my view.

In my controller I have

previous_three_days = Date.today - 3
@results = Result.where("fixture_date <= ?", previous_three_days)
@result_date = @results.group_by {|r| r.fixture_date}

In my view i then have this

   <% @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 %>

So whilst i am grouping by the fixture_date i would like to ensure that the home_team v away_team is unique, using .uniq does not work in this case.

My test data in this case looks like

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

and the output in the view is

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

which makes sense as i am grouping by fixture_date

Any help appreciated

4

2 回答 2

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 %>
于 2013-05-16T13:15:14.903 回答
1

为什么数据库中有重复项?也许你可以解决这个问题?

如果没有,您可以使用独特的

results = results.uniq { |r| r.home_team } 

上面贴的分组比较好,因为这样会更快更优雅

于 2013-05-16T13:18:50.650 回答