【问题标题】:How to scale count of unread messages in ActiveRecord scout app shows possible n+1 on the count(*) unread messages?如何在 ActiveRecord 侦察应用程序中缩放未读消息的计数在计数(*)未读消息上显示可能的 n+1?
【发布时间】:2018-07-25 09:51:59
【问题描述】:

如何在未读消息计数上删除 n+1,侦察应用在活动记录轨道的计数查询中显示可能的 n+1?

【问题讨论】:

    标签: ruby-on-rails database postgresql activerecord


    【解决方案1】:

    也许您正在寻找.includes?比如说Userhas_many :articles(和Articlebelongs_to :user),所以你可以Article.all.includes(:user)对所有用户进行一次查询,而不是为每个单独的用户进行单独的查询。

    文档:https://apidock.com/rails/ActiveRecord/QueryMethods/includes

    【讨论】:

    • SELECT COUNT(*) FROM "cmets" WHERE "cmets"."task_id" = ? AND (has_been_read = ? and user_id != ?) 这个查询导致 n+1
    • @user9361511 你到底是怎么得到这个查询的?是哪一行代码生成的?
    • 如果tasks.present? tasks.each 做 |as|如果 as.status !="Closed" 如果 as.comment.present? c_count = as.comment.where(:has_been_read => false).count comment_count += c_count > 0 ? c_count : 0 end end end end
    猜你喜欢
    • 2014-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    • 2018-08-28
    • 2015-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多