0

I am looping through an array of id's like so:

<% @tip.horse_ids.each do |i| %>
  <% @horse = Horse.find(i) %>
  <%= @horse.race.meeting.racecourse.strip %><br />
  <%= @horse.race.time.to_s(:time) %> - <%= @horse.name.strip %><br />
<% end %>

Which outputs something like this:

Kempton (AW)
01:30 - Light Gunner
Kempton (AW)
01:30 - Mesophere
Kempton (AW)
01:30 - Ragtag Rascal
Kempton (AW)
01:30 - Many Waters
Kempton (AW)
02:40 - Judicial
Stratford
01:40 - Rabunda
Stratford

I only want "Kempton (AW)" to appear once in the loop (the first one) and same for the time so "1:30" should only appear once too I want to remove all the duplicated content. Any help would be much appreciated, thanks!

3 Answers 3

1

Use uniq

@tip.horse_ids.uniq.each do |i|

or better yet

<% Horse.where(id: @tip.horse_ids).each do |horse| <%
  <%= horse.race.meeting.racecourse.strip %><br />
<% end %>

and even better, you should have access to horses if everything is set up correctly.

<% @tip.horses.each do |horse| <%
  <%= horse.race.meeting.racecourse.strip %><br />
<% end %>
Sign up to request clarification or add additional context in comments.

Comments

0

Adding a uniq to your array would solve your problem

<% @tip.horse_ids.uniq.each do |i| %>
  <% @horse = Horse.find(i) %>
  <%= @horse.race.meeting.racecourse.strip %><br />
  <%= @horse.race.time.to_s(:time) %> - <%= @horse.name.strip %><br />
<% end %>

Comments

0

If anyone has a similar problem to this the way I fixed it was by using group_by

<% @tip.horses.group_by(&:meeting).each do |meeting, horses| %>
  <%= meeting.racecourse %><br />
  <% horses.each do |horse| %>
    <%= horse.race.race_time %> - <%= horse.name %><br />
  <% end %>
<% end %>

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.