Navigating through relations on two paths in schem

2019-09-06 08:22发布

问题:

From top to bottom I have the belongs_to relationship between my tables , and well has_many from the other direction.

ReportTarget
Report  
Manager
Organization

and

Score
Manager
Organization

so notice that Report table and Score table are kind of on the same level. They both have Manager Table as their parent.

Individually I could figure out how to navigate them with eager loading. For first one I will do:

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

and for the second one I can do this:

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

But because I am doing with in my controller and want to pass the JSON to JBuilder, I don't know how to pass both of them? or maybe combine them together? such that resulting hash would have them in one hash but with separate keys:

{
  "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:

Use two different instance variables,

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

and then just use those inside the .json.jbuilder view file