2012-07-30 95 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