title: Rails postgres best way to optimize query - to populate a calendar view
body: <p>I want to construct a calendar full month view that looks like this (simplistically):</p>
  
  <pre><code>user        1   2   3   4   5   6   7   8   9   10   ...
  user one            X           X       X
  user two    X           X   X
  </code></pre>
  
  <p>Where 1..31 across the top is the calendar dates</p>
  
  <p>This is sourced from the following models</p>
  
  <pre><code>user has_many leave_requests
  
  leave_request belongs_to user
  leave_request has_many leave_days
  
  leave_day belongs_to leave_request
  </code></pre>
  
  <p>Currently, the only way I can get this to work is brute force it like this (this is pseudo-coded to save space - it's not the way I want to do it):</p>
  
  <pre><code>&lt;%
  @users = User.all
  @users.each do |user|
  %&gt;
    &lt;tr&gt;
        &lt;td&gt;&lt;%= user.name %&gt;&lt;/td&gt;
        &lt;% (1..31).each do |day| %&gt;
          &lt;% user.leave_request.each do |lr| %&gt;
            &lt;% lr.leave_dates.each do |ld| %&gt;
              &lt;% if ld.date_requested == day %&gt;
                &lt;% text = day.date_requested %&gt;
              &lt;% else %&gt;
                &lt;% text = "" %&gt;
              &lt;% end %&gt;
              &lt;td&gt;&lt;%= text %&gt;&lt;/td&gt;
            &lt;% end %&gt;
          &lt;% end %&gt;
        &lt;% end %&gt;
    &lt;/tr&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p>I guess, what I'm really looking for is a way to map the dates from the leave_days table onto a calendar month. I don't mind a bit of complexity but this brute force approach just feels wrong</p>