Ruby on rails rails3嵌套包括哪些内容?
有没有合适的方法来写这篇文章,或者我的做法是错误的?我需要做一个嵌套包含。我找到了,但似乎不起作用Ruby on rails rails3嵌套包括哪些内容?,ruby-on-rails,ruby-on-rails-3,activerecord,Ruby On Rails,Ruby On Rails 3,Activerecord,有没有合适的方法来写这篇文章,或者我的做法是错误的?我需要做一个嵌套包含。我找到了,但似乎不起作用 def show @showring = Ring.includes(:stones => :upcharges, :variations).find(params[:id]) end 我有三张桌子。。。 有许多石头的戒指 有许多上升电荷的石头 型号: class Ring < ActiveRecord::Base has_many :stones end class
def show
@showring = Ring.includes(:stones => :upcharges, :variations).find(params[:id])
end
我有三张桌子。。。
有许多石头的戒指
有许多上升电荷的石头
型号:
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
class-Ring
添加了一些括号:)
获取所有升级费用:
@showring.stones.each do |s|
s.upcharges #Do whatever you need with it
end
选项2:声明一个有多个:通过
class Ring < ActiveRecord::Base
has_many :stones
has_many :upcharges, :through => :stones
end
class-Ring:石头
结束
然后在视图中:
<%= @showring.upcharges.to_json.html_safe %>
好的,控制器中没有错误,因此我认为它可能工作正常。但在我看来(JSON),我得到了#ActiveRecord::Relation:0x007FE12DC2B350的未定义方法“upcharges”,这是因为您必须迭代@showring.stones
。它是一个集合,因此您不能直接对其调用。upcharges
。我用一个例子编辑了我的答案谢谢。我试试看。我认为.to_json会自动在集合上迭代…是的,但是你想做什么<代码>@showring.stones.upcharges
?您不能直接在has_many association返回的数组上调用关联。在my show.json.erb中,我有:“upcharges”:
<%= @showring.upcharges.to_json.html_safe %>