render :json => {
"playlist" => playlist_description,
"songs" => @playlist.songs.as_json(:include => {:playlist_songs => {:only => [:id, :position]}})
}
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.
This is so slow, how can I optimize?
My guess: You’re not eager-loading the playlist_songs at the moment. You’re currently waiting until the as_json call – after which all the songs have been loaded – and then the code has to iterate over every song and fetch the playlist_songs then.
My guess (this is totally untested and may include bugs)
AFAICT, this should first eager load all the songs and the playlist_songs… and then render as json.