title: Rails/Sql - order/group search results such that repetition of entities occurs only after appearance of others
body: <p>In my application, say, animals have many photos. I'm querying photos of animals such that I want all photos of all animals to be displayed. However, I want each animal to appear as a photo before repetition occurs. </p>
  
  <pre><code>Example: 
  
  animal instance 1, 'cat', has four photos, 
  animal instance 2, 'dog', has two photos:
  
  photos should appear ordered as so:
  
  #photo         belongs to     #animal
  
  tiddles.jpg ,                  cat 
  fido.jpg                       dog 
  meow.jpg                       cat 
  rover.jpg                      dog 
  puss.jpg                       cat 
  felix.jpg,                     cat  (no more dogs so two consecutive cats)
  </code></pre>
  
  <ul>
  <li>Pagination is required so I can't
  order on an array.  </li>
  <li>Filename
  structure/convention provides no
  help, though the animal_id exists on
  each photo. </li>
  <li>Though there are two
  types of animal in this example this
  is an active record model with
  hundreds of records. </li>
  <li>Animals may be
  selectively queried.</li>
  </ul>
  
  <p>If this isn't possible with active_record then I'll happily use sql; I'm using postgresql.</p>
  
  <p>My brain is frazzled so if anyone can come up with a better title, please go ahead and edit it or suggest in comments.</p>