2011-11-28 104 views
7
render :json => { 
    "playlist" => playlist_description, 
    "songs" => @playlist.songs.as_json(:include => {:playlist_songs => {:only => [:id, :position]}}) 
    } 

上面的代碼導致1 + N查詢到數據庫,一個爲每首歌曲加載playlist_songs。 播放列表已預載入@playlist。Rails:渴望加載as_json包括

這太慢了,我該如何優化?

回答

17

我的猜測:你不是急於加載此刻的playlist_songs。您目前正在等待as_json調用 - 之後所有歌曲都已加載 - 然後代碼必須遍歷每首歌曲,然後獲取playlist_songs。

我的猜測(這是完全未經測試,可能包括錯誤)

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

AFAICT,這應該第一貪婪加載的所有歌曲的playlist_songs ...然後呈現爲JSON。

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

^猜

4

我強烈建議與JSON構建器集成,如rabl。它將使您的生活更容易前進10倍,並且非常好地分離JSON表示的「視圖」。幾個月前我做了開關,並沒有回頭。

在你的控制器:

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

然後Rabl的模板可能是這樣的:

object @playlist 
attribute :description 
child :playlist_songs do 
    attributes :id, :position 
end