Paul Meier
Paul Meier

Reputation: 117

Rails association access

I wish I described this better, but it's the best I know how. I have two classes Cars and Colors. Each can have many of each other through a association class CarColors. The association is set up correctly I'm positive of this but I can't seem to get this to work:

@carlist = Cars.includes(:Colors).all

@carlist.colors

ERROR

@carlist[0].colors

WORKS

My question is how can I iterate over the @carlist without declaring a index as in the successful example? Below is a few things I have tried which also fail:

@carlist.each do |c|
c.colors
end

@carlist.each_with_index do |c,i|
c[i].colors
end

Upvotes: 3

Views: 203

Answers (1)

Dan McClain
Dan McClain

Reputation: 11920

Your first example fails because Car.includes(:colors).all returns an array of cars, not a single car, so the following will fail, because #colors is not defined for the array

@cars = Car.includes(:colors).all
@cars.colors #=> NoMethodError, color is not defined for Array

The following will work, because the iterator will have an instance of car

@cars.each do |car|
  puts car.colors # => Will print an array of color objects
end

each_with_index will work as well, but it is a bit different, as the first object is the same as the each loop car object, the second object is the index

@cars.each_with_index do |car, index|
  puts car.colors # => Will print an array of color objects
  puts @cars[index].colors # => Will print an array of color objects
  puts car == @cars[index] # => will print true
end

Upvotes: 1

Related Questions