ruby-on-rails – Ruby on Rails平均方法导致n 1个查询

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Ruby on Rails平均方法导致n 1个查询前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下脚本:
User.includes(:owned_ratings).map{|x| x.owned_ratings.average(:score)}

调用x.owned_ratings.average(:score)会导致n 1个查询

(0.2ms)  SELECT AVG("ratings"."score") FROM "ratings" INNER JOIN "video_chats" ON "ratings"."video_chat_id" = "video_chats"."id" WHERE "video_chats"."user_id" = $1  [["user_id",4]]
   (0.1ms)  SELECT AVG("ratings"."score") FROM "ratings" INNER JOIN "video_chats" ON "ratings"."video_chat_id" = "video_chats"."id" WHERE "video_chats"."user_id" = $1  [["user_id",1]]
   (0.1ms)  SELECT AVG("ratings"."score") FROM "ratings" INNER JOIN "video_chats" ON "ratings"."video_chat_id" = "video_chats"."id" WHERE "video_chats"."user_id" = $1  [["user_id",5]]
   (0.1ms)  SELECT AVG("ratings"."score") FROM "ratings" INNER JOIN "video_chats" ON "ratings"."video_chat_id" = "video_chats"."id" WHERE "video_chats"."user_id" = $1  [["user_id",7]]
   (0.1ms)  SELECT AVG("ratings"."score") FROM "ratings" INNER JOIN "video_chats" ON "ratings"."video_chat_id" = "video_chats"."id" WHERE "video_chats"."user_id" = $1  [["user_id",3]]

为什么包含不使用聚合方法?有什么方法可以解决这个问题吗?我知道我可以自己实现平均方法并省略问题,但我想确保没有更好的解决方案.

解决方法

Why includes is not working with aggregate methods?

因为在ruby中重新实现聚合方法没有意义,所以当数据库服务器可以更快地完成工作时.

实际上,如果这是您需要做的,那么准备和执行原始SQL查询可能会更好,因此整个迭代都在数据库中完成,因此避免了往返和N 1(更不用说加载所有内容).

猜你在找的Ruby相关文章