我正在将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
有更好的解决方案吗?
答案 0 :(得分:5)
Rails有from
方法。所以我会写下来:
NotificationMessage
.from(
NotificationMessage
.select("type, date(created_at)")
.group("type, date(created_at)"), :x
).count