我正在尝试让这些查询返回一个id为这样的哈希:
{[08/14/2015, [... records ...]],[08/15/2015, [... records ...]]}
使用以下代码执行此操作:
@trucks = Truck.where(:company_id => 33)
@trucks_by_date = @trucks.group_by(&:available)
=> {[Fri, 14 Aug 2015 00:00:00 UTC +00:00, [... records ...]], [Sat, 15 Aug 2015 00:00:00 UTC +00:00, [... records ...]]}
我试过这个,但错了:
@trucks.group_by("CAST(available AS DATE)")
--- AND ---
@trucks.group("DATE(available)")
=> 1.9.3-p551 :074 > @trucks_by_date = @trucks.group("DATE(available)")
Truck Load (74.2ms) SELECT "trucks".* FROM "trucks" WHERE "trucks"."company_id" = 33 GROUP BY DATE(available)
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR: column "trucks.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT "trucks".* FROM "trucks" WHERE "trucks"."company_id"...
^
: SELECT "trucks".* FROM "trucks" WHERE "trucks"."company_id" = 33 GROUP BY DATE(available)
from /usr/local/rvm/gems/ruby-1.9.3-p551@loadmax/gems/activerecord-3.2.3/lib/active_record/connection_adapters/postgresql_adapter.rb:1139:in `async_exec'
from /usr/local/rvm/gems/ruby-1.9.3-p551@loadmax/gems/activerecord-3.2.3/lib/active_record/connection_adapters/postgresql_adapter.rb:1139:in `exec_no_cache'
from /usr/local/rvm/gems/ruby-1.9.3-p551@loadmax/gems/activerecord-3.2.3/lib/active_record/connection_adapters/postgresql_adapter.rb:663:in `block in exec_query'
如果我这样做:(日期格式也错误)
@trucks_by_date = @trucks.group("DATE(available)").count
=> `{"2015-08-13"=>5, "2015-07-27"=>3, "2015-08-18"=>2, "2015-08-14"=>6, "2015-08-17"=>1, "2015-07-31"=>2, "2015-08-12"=>5, "2015-08-11"=>8, "2015-07-30"=>4, "2015-08-10"=>13, "2015-08-07"=>4, "2015-08-03"=>4, "2015-07-24"=>1, "2015-07-28"=>5}`
但我不想要数,我想要完整的记录。
原因:我有一个初始化程序,可以更改数据格式,如下所示:
Date::DATE_FORMATS[:default] = "%m/%d/%Y"
Time::DATE_FORMATS[:default] = "%m/%d/%Y"
当我尝试通过哈希迭代它改变格式,因此它无法找到哈希的正确位置
答案 0 :(得分:1)
@trucks = Truck.where(:company_id => 33)
@trucks_by_date = @trucks.group_by {|t| t.available.to_s(:default) }