通过Active Record查询界面编写postgres查询

时间:2015-02-18 17:55:12

标签: ruby-on-rails postgresql

我在Postgres中运行以下查询:

SELECT count(id), to_char(current_sign_in_at, 'yyyy-MM-dd') AS sign_in_date
From users
WHERE current_sign_in_at > date '2014-02-16'
GROUP by sign_in_date;

当我通过ActiveRecord :: Base.connection.execute运行此查询时,我得到:

[{"count"=>"3", "sign_in_date"=>"2015-02-17"}, {"count"=>"1", "sign_in_date"=>"2014-10-26"}, {"count"=>"1", "sign_in_date"=>"2014-10-18"}]

我无法使用活动记录查询界面让查询工作。

1 个答案:

答案 0 :(得分:0)

这是一种Rails方式:

@users = User.group(:sign_in_date)
             .where("current_sign_in_at > date (?)", '2014-02-16')
             .select("count(id) AS count, to_char(current_sign_in_at, 'yyyy-MM-dd') AS sign_in_date")

现在,按照问题中提到的,运行 direct sql,遍历@users以获得结果。

@users.map { |user| {"count"=> user.count, "sign_in_date"=> user.sign_in_date} }
相关问题