2012-08-14 93 views
3

我希望我更好地描述這一點,但它是我知道的最好的方法。我有兩類汽車和顏色。每個人都可以通過CarColors的關聯課彼此擁有許多關係。該協會建立正確我敢肯定這一點,但我似乎無法得到這個工作:Rails協會訪問

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

@carlist.colors 

錯誤

@carlist[0].colors 

WORKS

我的問題是我怎麼可以遍歷@carlist沒有聲明一個成功的例子索引?下面是幾件事情我已經試過這也失敗:因爲Car.includes(:colors).all返回汽車,而不是一個單一的汽車組成的數組

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

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

我認爲你必須做一些與顏色,請嘗試在每個塊中打印它 @ carlist.each do | c | p c.colors end – 2012-08-14 14:41:00

+0

當你在做'@carlist.each_with_index do | c,i | c [i] .colors end'應該是'@carlist.each_with_index do | c,i | @carlist [i] .colors'結尾 – 2012-08-14 14:46:10

回答

1

你的第一個例子失敗了,所以下面將失敗,因爲#colors沒有爲數組定義

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

下面的工作,因爲迭代器都將有車

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

的實例0也能發揮作用,但它是一個有點不同,作爲第一個對象 是一樣的每個循環車對象,第二個對象是指數

@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 
+0

它的'@cars [index] .colors'和'car == @cars [index]' – 2012-08-14 14:57:38

+0

@ShreyasAgarwal:謝謝,錯過了那些! – 2012-08-14 14:58:34

+0

另外,僅僅爲了迭代所有項目而使用'#all',這是一個糟糕的主意。 – Hauleth 2012-08-14 15:00:51