0

Going a bit mad here.

@sport = Sport.find(params[:sport])
@activities = Activity.where("sport_id = ?", @sport)

@activites outputs fine with the below:

<% @activities.each do |a| %>
  <%= a.id %>
<% end %>

showing 2 values as predicted.

My problem is, when I write (in the controller):

for a in @activities
  @facilities = Facility.where("id = ?", a.facility_id)
end

My output for:

<% @facilities.each do |f| %>
  <%= f.id %>
<% end %>

only returns 1 value. It should show 2 values as each of the above activities belong to different facilities. I think it is either something to do with the for loop OR when I define @facilities it is only registering one value.

Any help? Thanks :)

1
  • Don't use for, use each or map, depending on your goal. The latter are idiomatic Ruby. Commented Oct 6, 2014 at 22:40

2 Answers 2

4

The problem is that you are re-assigning @facilities on each iteration of the loop. I think you want something more like:

@facilities = []
for a in @activities
  @facilities << Facility.find(a.facility_id)
end

This might be better written as

@facilities = @activities.map {|a| Facility.find(a.facility_id) }

But, preferably, you've defined an association for :facility

@facilities = @activities.map {|a| a.facility}
Sign up to request clarification or add additional context in comments.

1 Comment

Ahhhh THATS what I was looking for. I knew the problem but no solution. Thank you sir!
1

You're right:

... when I define @facilities it is only registering one value.

For each iteration of this loop:

for a in @activities
  @facilities = Facility.where("id = ?", a.facility_id)
end

you're clobbering the previous value in @facilities and replacing it with a new one. At the end of the loop, only the final value of Facility.where("id = ?", a.facility_id) is retained.

Instead, you could use map to obtain an array of all of the facilities:

@facilities = @activites.map do |a|
  Facility.where("id = ?", a.facility_id)
end

Then continue in your view as you did before:

<% @facilities.each do |f| %>
  <%= f.id %>
<% 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.