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

回眸只為那壹抹淺笑 提交于 2020-01-04 06:33:24

问题


I'm migrating an SQL query to Active Record. Here is a simplified version:

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

I'm not sure how to implement this in Active Record. This works, but it's messy:

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

Another possibility is to do the count in Ruby, but that would be less efficient:

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

Is there a better solution?


回答1:


Rails has the from method. So I would write it:

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


来源:https://stackoverflow.com/questions/35517078/how-do-you-get-a-count-of-a-subquery-in-active-record

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!