Rails:急切地加载as_json包括 [英] Rails: Eager loading as_json includes

查看:118
本文介绍了Rails:急切地加载as_json包括的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

上面的代码对数据库产生1 + N个查询,每个查询都会加载一首歌的playlist_songs。
播放列表已预加载到@playlist中。

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.

这太慢了,如何优化?

推荐答案

我的猜测:您现在不急于加载playlist_songs。您当前正在等待as_json调用(此后所有歌曲均已加载),然后代码必须遍历每首歌曲,然后获取playlist_song。

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)

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

AFAICT,这应该首先渴望加载所有歌曲 playlist_songs ...然后呈现为json。

AFAICT, this should first eager load all the songs and the playlist_songs... and then render as json.

这篇关于Rails:急切地加载as_json包括的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆