title: Complex Rails/Postgres SQL optimization
body: <p>Restaurant
      has_many Dish</p>
  
  <pre><code>Dish
  has_many Photo
  
  Photo
  belongs_to Dish
  
  Restaurant 1
    Dish 1
      Photo 1   May 9, 1:00 PM
    Dish 2
      Photo 2   May 9, 2:00 PM
    Dish 3
      Photo 3   May 9, 3:00 PM
  
  Restaurant 2
    Dish 4
      Photo 4   May 9, 1:00 PM
    Dish 5
      Photo 5   May 9, 2:00 PM
    Dish 6
      Photo 6   May 9, 3:00 PM
  </code></pre>
  
  <p>I'm trying to retrieve the latest 50 photos with a limit of 2 dish photos per restaurant. Given the data above I'd be able to retrieve photos with ids <code>2, 3, 5, and 6</code></p>
  
  <p>My current implementation is ugly to say the least.</p>
  
  <pre><code>hash = {}
  bucket = []
  Photo.includes(:dish =&gt; [:restaurant]).order("created_at desc").each do |p|
    restaurant_id = p.dish.restaurant.id
    restaurant_count = hash[restaurant_id].present? ? hash[restaurant_id] : 0
    if restaurant_count &lt; 2
      bucket &lt;&lt; p
      hash[restaurant_id] = restaurant_count + 1
    end
    # if you've got 50 items short circuit.
  end
  </code></pre>
  
  <p>I can't help but feel that there's a much more efficient solution. Any ideas would be appreciated :-).</p>