playlist_description, "songs" => @playlist.songs.as_json(:include => {:playlist...">

Rails: active as_json loading enable

render :json => { "playlist" => playlist_description, "songs" => @playlist.songs.as_json(:include => {:playlist_songs => {:only => [:id, :position]}}) } 

The above code leads to 1 + N queries in the database, one for loading playlist_songs for each song. The playlist is preloaded to the @playlist.

It is so slow, how can I optimize?

+7
source share
3 answers

My guess: you do not want to download playlist_songs at the moment. You are currently waiting for as_json to call, after which all the songs have been downloaded, and then the code should iterate over each song and then get the playlist.

My guess (this is completely untested and may contain errors)

 @playlist.songs.all(:include => :playlist_songs).as_json(:include => {:playlist_songs => {:only => [:id, :position]}}) 

AFAICT, first you need to download all the songs and playlist_songs ... and then do it like json.

+17
source

I highly recommend integrating with a JSON builder like rabl . It will simplify your life by 10 times, and itโ€™s very nice to separate the โ€œpresentationโ€ from the JSON representation. I made the transition a couple of months ago and did not look back.

Inside your controller:

 @playlist = Playlist.where(:id => params[:id]).includes(:playlist_songs) 

Then the rabl pattern could be something like this:

 object @playlist attribute :description child :playlist_songs do attributes :id, :position end 
+4
source
 render :json => { "playlist" => playlist_description, "songs" => @playlist.songs.all.as_json(:include => {:playlist_songs => {:only => [:id, :position]}}) } 

^ guess

+1
source

All Articles