rails 3按日期分组日期时间列

ast*_*nic 20 datetime ruby-on-rails-3

Foo.group(:start_at).count(:id)
Run Code Online (Sandbox Code Playgroud)

我如何按日期分组?"start_at"列是日期时间列

Dav*_*ulc 38

这应该工作(rails 3):

Foo.order(:start_at).group("DATE(start_at)").count
Run Code Online (Sandbox Code Playgroud)

编辑:如果你正在使用PostgreSQL,那么查询应该是

Foo.order("DATE(start_at)").group("DATE(start_at)").count
Run Code Online (Sandbox Code Playgroud)

或者你会收到一个错误

("PGError: ERROR:  column "foos.start_at" must appear in the GROUP BY clause or be used in an aggregate function")
Run Code Online (Sandbox Code Playgroud)

基于

使用Seer在Rails应用程序中按日期绘制新用户

http://www.pastbedti.me/2009/11/grouping-a-timestamp-field-by-date-in-ruby-on-rails-postgresql/


And*_*ane 9

我为此创造了一个宝石.https://github.com/ankane/groupdate

Foo.group_by_day(:created_at).count
Run Code Online (Sandbox Code Playgroud)

您甚至可以指定时区.

Foo.group_by_day(:created_at, time_zone: "Pacific Time (US & Canada)").count
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法用这个宝石获得物品而不是计数? (2认同)