我希望我能更好地描述这一点,但这是我所知道的最好的方法。我有两个类(class)汽车和颜色。每个人都可以通过关联类 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
返回了一组汽车,而不是一辆车,所以下面的例子会失败,因为 #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
也可以,但有点不同,因为第一个对象
和each loop car对象一样,第二个对象是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
关于ruby-on-rails - Rails 关联访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11954637/