在Rails中,我想在页面上显示每天“创建”有多少新“用户”。
在常规SQL中,我会做类似的事情:
SELECT
DATE(created_at) as day,
COUNT(1) as new_user_count
FROM users
WHERE created_at > '2014-01-01 01:01:01'
GROUP BY day
如何针对Rails中的Users
表执行此操作?同样,我需要在页面上显示这个,所以我不是在PG GUI上寻找指令。
具体来说,我正在使用Heroku和Postgres。
答案 0 :(得分:1)
这样做:
sql = "SELECT DATE(created_at) as day, COUNT(1) as new_user_count " \
"FROM users WHERE created_at > '2014-01-01 01:01:01' " \
"GROUP BY day"
ActiveRecord::Base.connection.execute(sql)
答案 1 :(得分:0)
除了原始SQL解决方案之外,您可以考虑创建一个视图:
create view daily_user_counts as
SELECT
DATE(created_at) as day,
COUNT(*) as new_user_count
FROM users
WHERE created_at > '2014-01-01 01:01:01'
GROUP BY day;
...并为其创建只读模型:
class DailyUserCount < ActiveRecord::Base
def readonly?
true
end
end
然后:
DailyUserCount.where("day > ? ", from).order(:day)