1

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

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"

我在数据库保存之前创建了一个有效的 DateTime 对象,因为我已经使用记录器来显示它并且它是正确的。参数如下所示:

{"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 来通过控制台创建记录。

4

1 回答 1

2

错误消息很清楚:语句中的您是类型$2而不是类型(日期时间)INSERTtimetimestamp

插入“班次”

(“created_at”、“ end_at ”、“notes”、“位置”、“schedule_id”、“start_at”、“updated_at”、“user_id”)

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

强调我的。您必须混淆参数,$2显然不是您在发布结束时显示的参数。或者您在分配之前无意中将其转换为时间。您分配的部分在$2问题中不可见,这很可能是问题发生的地方。

也许在您提到的问题中出现了某种错字,timedate而不是datetime?

于 2011-11-14T05:00:24.810 回答