rails3嵌套包括?

Joe*_*nas 2 activerecord ruby-on-rails ruby-on-rails-3

是否有正确的方法来写这个,或者我是否接近这个错误?我需要做一个嵌套的include.我找到了这个链接,但似乎没有用.

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

我有3张桌子......有多块石头的戒指有很多人加起来的石头

楷模:

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
Run Code Online (Sandbox Code Playgroud)

Ant*_*rto 7

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

添加了一些括号:)

获得所有增加费用:

@showring.stones.each do |s|
  s.upcharges #Do whatever you need with it
end
Run Code Online (Sandbox Code Playgroud)

选项2:声明一个 has_many :through

class Ring < ActiveRecord::Base
  has_many :stones
  has_many :upcharges, :through => :stones
end
Run Code Online (Sandbox Code Playgroud)

然后在视图中:

<%= @showring.upcharges.to_json.html_safe %>
Run Code Online (Sandbox Code Playgroud)