在模式中的两条路径上导航关系

时间:2013-03-01 18:54:13

标签: ruby-on-rails ruby-on-rails-3.2 rails-activerecord eager-loading

从上到下,我的表之间有belongs_to关系,而另一个方向的has_many很好。

ReportTarget
Report  
Manager
Organization

Score
Manager
Organization

请注意Report表和Score表在同一级别上。他们都有Manager表作为他们的父母。

单独地,我可以弄清楚如何通过急切加载来导航它们。 对于第一个,我会做:

@blah = Organization.includes(managers: { reports: :report_targets }).find(params[:id])

对于第二个我可以这样做:

@blah = Organization.includes([managers: :scores]).find(params[:id])

但是因为我在我的控制器中做了并且想要将JSON传递给JBuilder,我不知道如何传递它们?或者将它们组合在一起?这样产生的散列会将它们放在一个散列中,但是使用单独的键:

{
  "firstoneinfo" : [
     # stuff that first json returns, can have their own internal hashes
     ],
   "SecondOneinfo : [
    #stuff that second json returns, can have their own internal hashes
    ]
}

1 个答案:

答案 0 :(得分:1)

使用两个不同的实例变量

@firstoneinfo =  Organization.includes(managers: { reports: :report_targets }).find(params[:id])
@SecondOneInfo = Organization.includes([managers: :scores]).find(params[:id])

然后只使用.json.jbuilder视图文件中的那些