您如何获得 Active Record 中子查询的计数?

How do you get a count of a subquery in Active Record?

我正在将 SQL 查询迁移到 Active Record。这是一个简化版本:

SELECT count(*) FROM (
  SELECT type, date(created_at)
  FROM notification_messages
  GROUP BY type, date(created_at)
) x

我不确定如何在 Active Record 中实现它。这行得通,但很乱:

sql = NotificationMessage.
  select("type, date(created_at) AS period").
  group("type", "period").
  to_sql
NotificationMessage.connection.exec_query("SELECT count(*) FROM (#{sql}) x")

另一种可能性是在 Ruby 中进行计数,但效率较低:

NotificationMessage.
  select("type, date(created_at) AS period").
  group("type", "period").
  length

有更好的解决方案吗?

Rails 有 from 方法。所以我会这样写:

NotificationMessage
  .from(
    NotificationMessage
      .select("type, date(created_at)")
      .group("type, date(created_at)"), :x
  ).count