如何计算Active Record中的子查询?

时间:2016-02-19 23:38:01

标签: ruby-on-rails postgresql subquery rails-activerecord

我正在将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

有更好的解决方案吗?

1 个答案:

答案 0 :(得分:5)

Rails有from方法。所以我会写下来:

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