在Postgres上使用Rails的Datetime字段

时间:2011-11-13 19:35:35

标签: ruby-on-rails postgresql activerecord rails-postgresql

我正在使用Rails与Postgres制作调度应用程序。我有一个带有两个时间日期列的模型Shift,start_at和end_at。创建它的迁移如下:

class CreateShifts < ActiveRecord::Migration
  def change
    create_table :shifts do |t|
      t.references :user
      t.references :schedule
      t.datetime :start_at
      t.datetime :end_at
      t.string :position
      t.string :notes

      t.timestamps
    end
    add_index :shifts, :user_id
    add_index :shifts, :schedule_id
  end
end

当我尝试创建记录时,我得到以下错误500输出:

GError: ERROR:  column "end_at" is of type timestamp without time zone but expression is of type time without time zone at character 132
HINT:  You will need to rewrite or cast the expression.
: INSERT INTO "shifts" ("created_at", "end_at", "notes", "position", "schedule_id", "start_at", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING "id"

我在DB保存之前创建了一个有效的DateTime对象,因为我已经使用了记录器来显示它并且它是正确的。 params看起来像这样:

{"utf8"=>"✓",
 "authenticity_token"=>"qornHMTAdikZJP/sByPIg//fFuYHHAQH3M/0R9XnP+o=",
 "shift"=>{"user_id"=>"1",
 "start_at(1i)"=>"2011",
 "start_at(2i)"=>"11",
 "start_at(3i)"=>"14",
 "start_at(4i)"=>"00",
 "start_at(5i)"=>"01",
 "end_at(1i)"=>"2011",
 "end_at(2i)"=>"11",
 "end_at(3i)"=>"14",
 "end_at(4i)"=>"00",
 "end_at(5i)"=>"02",
 "position"=>"",
 "notes"=>""},
 "schedule_id"=>"1"}

但是,我可以通过将两个字段都设置为Time.now来创建记录。

1 个答案:

答案 0 :(得分:2)

错误信息非常清楚: $2语句中的INSERT类型为time,而不是类型timestamp(日期时间)

  

INSERT INTO“shift”

     

(“created_at”,“ end_at ”,“注释”,“位置”,“schedule_id”,“start_at”,“updated_at”,“user_id”)

     

VALUES($ 1, $ 2 ,$ 3,$ 4,$ 5,$ 6,$ 7,$ 8)返回“id”

强调我的。 您必须混合参数,$2显然不是您在发布结束时显示的参数。或者你在分配之前无意中把它投到了时间。您指定$2的部分在问题中不可见,这是问题发生的地方,很可能。

在您提问timedate而不是datetime的问题中,可能会出现某种错字?