Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 252
Patrick Brinich-Langlois Avatar asked Sep 15 '25 08:09

Patrick Brinich-Langlois


1 Answers

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
like image 160
Arup Rakshit Avatar answered Sep 16 '25 22:09

Arup Rakshit