0

Having a Bit of trouble displaying unique results from my database. I have a database called "Activities". Each Activity has an associated Sport through sport_id. There may be many activities with the same sport_id.

I want to display a list of all sports linked to the activities database without displaying (for example "Football") twice.

FYI : Venues have many Facilities and Facilities have many Activities.

Controller:

@sports = Sport.all
@activities = Activity.paginate(page: params[:page])
@facilities = Facility.where(venue_id: @venue.id)

View:

<% @facilities.each do |f| %>
  <% @activities.find(:all, :conditions => "facility_id == #{f.id} ").each do |a| %>
   <li><%= Sport.find(a.sport_id).name %>, (<%= a.facility_id %>)</li>
  <% end %>
<% end %>

This shows:

  • Football, (2)
  • Hockey, (2)
  • Hockey, (2)
  • Football, (5)

I would like to display just:

  • Football
  • Hockey

Any ideas?

2
  • 2
    why not add a distinct condition in your request? what is unclear is that the different "hockey" element, are they part of different facilities or the same one? Commented Sep 15, 2014 at 10:06
  • Hi @tomsoft I have edited the questions to show the facility id in brackets. It shows that there are 3 activities in facility ID 3 and 1 activity in facility ID 5. Commented Sep 15, 2014 at 10:21

2 Answers 2

3

A simple solution would be to reduce your array with ruby in the view using: uniq!

<% @facilities.each do |f| %>
  <% @activities.find(:all, :conditions => "facility_id == #{f.id} ").uniq! { |a| a.sport_id }.each do |a| %>
    <li><%= link_to Sport.find(a.sport_id).name, Sport.find(a.sport_id) %></li>
  <% end %>
<% end %>

Another way may be to perform a single query on your DB since Sport what you want to narrow down

In controller:

@sports = Sport.joins(activities: [facility: :venue]).where(facilities: { venue_id: @venue.id }).distinct

In view:

<% @sports.each do |sport| %>
  <li><%= link_to sport.name, sport %></li>
<% end %>

I am not sure about your DB schema so I went with what I thought you would have done, but it might needs some tweakings.

I hope I helped you.

Sign up to request clarification or add additional context in comments.

1 Comment

Second way with the sports worked a treat! Thank you very much. I need to research further into "Joins". Thank you @Voxdei !
0

try to use reject before each

<% @facilities.reject{your condition here}.each do |f| %>

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.