使用rails控制台更改记录中的日期字段



我的数据库中存储了一个类型为time的对象。在Rails控制台中,如果我通过ID找到这个特定的记录,我会得到以下输出:

 id: 365,
 from_hours: Sat, 01 Jan 2000 01:00:00 UTC +00:00,
 to_hours: Sat, 01 Jan 2000 12:30:00 UTC +00:00

我想将from_hours字段更新为Sat, 01 Jan 2000 13:00:00 UTC +00:00

我该如何处理?

我尝试过使用MyRecord.find(365).update(from_hours: Sat, 01 Jan 2000 13:00:00 UTC +00:00),但没有成功。提前感谢!

如果将from_hours: Sat, 01 Jan 2000 01:00:00 UTC +00:00作为变量,则使用

MyRecord.find(365).update(from_hours: from_hours)

否则使用等报价内的时间

MyRecord.find(365).update(from_hours: 'Sat, 01 Jan 2000 13:00:00 UTC +00:00')

我建议不要直接使用更新,因为record也可以返回零,所以最好使用

if record = MyRecord.find(365)
  record.update(from_hours: 'Sat, 01 Jan 2000 13:00:00 UTC +00:00')
end

您需要在from_hours参数中添加引号:

MyRecord.find(365).update(from_hours: 'Sat, 01 Jan 2000 13:00:00 UTC +00:00')

使用.update!如果需要在控制台中获取引发异常。

最新更新