MikeHolford
MikeHolford

Reputation: 1931

Ruby for loop only using last value

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 :)

Upvotes: 0

Views: 247

Answers (2)

Travis Hohl
Travis Hohl

Reputation: 2196

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

Upvotes: 1

infused
infused

Reputation: 24337

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}

Upvotes: 4

Related Questions