title: Rails: Eager loading as_json includes
body: <pre><code>  render :json =&gt; {
      "playlist" =&gt; playlist_description,
      "songs" =&gt; @playlist.songs.as_json(:include =&gt; {:playlist_songs =&gt; {:only =&gt; [:id, :position]}})
    }
  </code></pre>
  
  <p>The above code results in 1+N queries to the database, one to load playlist_songs for each song.
  The playlist is preloaded in @playlist.</p>
  
  <p>This is so slow, how can I optimize?</p>