2016-02-19 90 views
1

我正在將SQL查詢遷移到Active Record。這裏是一個簡化版本:如何獲得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 

有沒有更好的解決辦法?

回答

4

Rails有from方法。所以我會寫它:

NotificationMessage 
    .from(
    NotificationMessage 
     .select("type, date(created_at)") 
     .group("type, date(created_at)"), :x 
).count 
相關問題