ruby-on-rails – Rails:渴望加载as_json包含

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rails:渴望加载as_json包含前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
render :json => {
    "playlist" => playlist_description,"songs" => @playlist.songs.as_json(:include => {:playlist_songs => {:only => [:id,:position]}})
  }

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

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

解决方法

我猜:你现在不急于加载playlist_songs.您当前正在等待as_json调用 – 之后所有歌曲都已加载 – 然后代码必须迭代每首歌曲然后获取playlist_songs.

我的猜测(这是完全未经测试的,可能包含错误)

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

AFAICT,这应该首先加载所有歌曲和playlist_songs …然后渲染为json.

原文链接:https://www.f2er.com/ruby/269196.html

猜你在找的Ruby相关文章