Rails:渴望加载as_json包含

时间:2011-11-28 21:39:09

标签: ruby-on-rails activerecord

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

上面的代码导致对数据库的1 + N个查询,一个为每首歌加载playlist_songs。 播放列表预装在@playlist中。

这太慢了,我该如何优化?

3 个答案:

答案 0 :(得分: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 :(得分:4)

我强烈建议您使用rabl等JSON构建器进行集成。它将使你的生活更容易前进,并且非常好地分离JSON表示的“视图”。几个月前我做了转换,但没有回头。

在您的控制器中:

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

然后rabl模板可能是这样的:

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

答案 2 :(得分:1)

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

^猜猜