这需要 5 秒

games = Game.where(league: 1).where.not(date: d).joins(:scores).select(:home_score)
puts games[-1].home_score

这需要 1 秒
games = Game.where(league: 1).where.not(date: d).joins(:scores).select(:home_score)

为什么第一段代码需要这么长时间?在我尝试打印数据之前查询是否不会运行?

最佳答案

你的猜测是对的。
games 是一个 ActiveRecord::Relation 对象,只有在真正需要数据时才会查询数据库。
games[-1] 将触发数据加载。

关于ruby-on-rails - Ruby Rails - 查询速度很快,直到我打印输出?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22523315/

10-13 09:34