我希望我能描述得更好,但这是我所知道的最好的方法。我有两个级别的车和颜色。每一个都可以通过一个关联类carcolors拥有许多彼此。协会设置正确我对此持肯定态度,但我似乎无法让它发挥作用:

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

@carlist.colors

误差
@carlist[0].colors

作品
我的问题是如何在不声明索引的情况下遍历@carlist,就像成功的例子中那样?以下是我尝试过的一些同样失败的事情:
@carlist.each do |c|
c.colors
end

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

最佳答案

您的第一个示例失败,因为Car.includes(:colors).all返回一个cars数组,而不是一个car,所以下面的示例将失败,因为#colors没有为数组定义

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

因为迭代器将有一个car实例
@cars.each do |car|
  puts car.colors # => Will print an array of color objects
end

each_with_index也可以工作,但作为第一个对象,它有点不同
与每个loop car对象相同,第二个对象是索引
@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

关于ruby-on-rails - Rails关联访问,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11954637/

10-14 16:04