title: How to sort deeply nested collections with ActiveRecord?
body: <p>I'm building a music-managing Rails app, and my app's users will be able to make ordered playlists of albums, and each album will have an ordered list of songs.</p>
  
  <p>In essence, this will look like:</p>
  
  <pre><code>class User &lt; ActiveRecord::Base
    has_many :playlists, :order =&gt; "position"
    has_many :albums, :through =&gt; :playlists
  end
  
  class Playlist &lt; ActiveRecord::Base
    belongs_to :user
    belongs_to :album
  end
  
  class Album &lt; ActiveRecord::Base
    has_many :songs, :order =&gt; "position"
    has_many :playlists
  end
  
  class Song &lt; ActiveRecord::Base
    belongs_to :album
  end
  </code></pre>
  
  <p>(I'm using <code>acts_as_list</code> to use a <code>position</code> column in the songs and playlists tables to manage the sort order of songs and playlists, respectively.)</p>
  
  <p>Now I'd like to find a list of all songs (in order) for a given user.  If I add this scope to the <em>Song</em> model:</p>
  
  <pre><code>scope :for_user, lambda{|user|
    joins(:album =&gt; {:playlists =&gt; :user}).
    where(:'users.id' =&gt; user.id)
  }
  </code></pre>
  
  <p>I can do just that, but the records returned aren't kept in order.  Instead, I'd like to see each song ordered first by its album's playlist position for the user, and then by the song's position in that album.  In other words, if a user wants to play albums A, B, and C in order, I'm looking for an array of all the songs from A (in the order they are on the album), plus all the songs from B (in order), plus all the songs from C (in order).</p>
  
  <p>I've tried several permutations of <em>order</em> and <em>group</em> clauses in the scope, but none has had the desired effect of ordering the songs within the context of ordering the albums.</p>