1

I have the following models

user

has_many :leave_balances

leave_balance

belongs_to :user
belongs_to :leave_type

leave_type

has_many :leave_balances

I want to output a table format showing user names and their balance by leave type. Not every user can have every balance i.e. outer joins required.

I'd like to see something like this:

Employee   Annual Leave   Sick Leave
Bob        10 
Fred                      9
Sara       12             15

I am unsure how to get this out as a single statement?

I am thinking something like User.joins(:leave_balances).joins(:leave_type)

Craig McGuff
  • 3,968
  • 6
  • 30
  • 35

2 Answers2

1

I recently faced this exact same thing. I switched to Squeel and I am much happier now. Specifically, the syntax for specifying an outer join is very clean:

result = User.joins { leave_balances.outer.leave_type.outer }.where { some_constraints }

https://github.com/ernie/squeel

0

You can pass a hash to joins method for nested joins

so you'll do

User.joins(leave_balances: :leave_type)

But that will perform an INNER JOIN, and I think that what you need is an LEFT OUTER JOIN

so you might have to manually write the join as described here

pjam
  • 6,356
  • 5
  • 30
  • 40