2012-07-30 93 views
2

有沒有正確的方法來寫這個,或者我接近這個錯誤?我需要做一個嵌套包含。我發現This Link,但它似乎沒有工作。rails3嵌套包括?

def show 
    @showring = Ring.includes(:stones => :upcharges, :variations).find(params[:id]) 
end 

我有3個表... 戒指其中的has_many石頭 石塊的has_many upcharges

型號:

class Ring < ActiveRecord::Base 
    has_many :stones 
end 

class Stone < ActiveRecord::Base 
    has_many :upcharges 
    belongs_to :ring 
end 

class Upcharge < ActiveRecord::Base 
    belongs_to :stone 
end 

回答

7
def show 
    @showring = Ring.includes([{:stones => :upcharges}, :variations]).find(params[:id]) 
end 

添加了一些括號:)

獲取全部上漲:

@showring.stones.each do |s| 
    s.upcharges #Do whatever you need with it 
end 

選項2:聲明has_many :through

class Ring < ActiveRecord::Base 
    has_many :stones 
    has_many :upcharges, :through => :stones 
end 

然後在視圖:

<%= @showring.upcharges.to_json.html_safe %> 
+0

好了,它在控制器不錯誤,所以我認爲這可能是工作。但在我看來(JSON)我得到了未定義的方法'upcharges'爲#< ActiveRecord :: Relation:0x007fe12dc2b350 > – 2012-07-30 21:00:05

+0

這是因爲你必須遍歷'@ showring.stones'。這是一個集合,因此你不能直接調用'.upcharges'。我編輯我的答案,例如 – 2012-07-30 21:01:27

+0

謝謝。我會嘗試。我以爲.to_json自動迭代集合... – 2012-07-31 12:34:33