playlist_description, "songs" => @playlist.songs.as_json(:in-6ren">
gpt4 book ai didi

ruby-on-rails - Rails : Eager loading as_json includes

转载 作者:行者123 更新时间:2023-12-04 04:55:40 25 4
gpt4 key购买 nike

  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。

关于ruby-on-rails - Rails : Eager loading as_json includes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8302715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com