日期时间无法保存但没有错误

时间:2015-08-14 02:09:47

标签: ruby-on-rails sqlite datetime ruby-on-rails-4

我尝试保存一个具有名为class_datetime的属性(DateTime)的行,它会无声地失败。这是一个例子:

我创建了一个新的LittleClassSession,如下所示:

irb(main):010:0> l = LittleClassSession.new
=> #<LittleClassSession id: nil, length: nil, class_datetime: nil, created_at: nil, updated_at: nil, little_class_id: nil, location_id: nil, session_series_token: nil>

class_datetimeDateTime

irb(main):011:0> LittleClassSession.columns_hash["class_datetime"].type
=> :datetime

我设置了属性:

irb(main):012:0> l.class_datetime = DateTime.now
=> 2015-08-13 22:02:09 -0400

我保存(尚无验证):

irb(main):013:0> l.save
   (0.1ms)  begin transaction
  SQL (0.4ms)  INSERT INTO "little_class_sessions" ("class_datetime", "created_at", "updated_at") VALUES (?, ?, ?)  [["class_datetime", "2015-08-13 22:02:09.976030"], ["created_at", "2015-08-13 22:03:01.255911"], ["updated_at", "2015-08-13 22:03:01.255911"]]
   (2.6ms)  commit transaction
=> true

看起来很有效。让我们看看我保存了什么:

irb(main):014:0> l
=> #<LittleClassSession id: 728, length: nil, class_datetime: "2015-08-14 02:02:09", created_at: "2015-08-14 02:03:01", updated_at: "2015-08-14 02:03:01", little_class_id: nil, location_id: nil, session_series_token: nil>

让我们看看表中的内容:

irb(main):015:0> LittleClassSession.last
  LittleClassSession Load (0.2ms)  SELECT  "little_class_sessions".* FROM "little_class_sessions"   ORDER BY "little_class_sessions"."id" DESC LIMIT 1
=> #<LittleClassSession id: 728, length: nil, class_datetime: nil, created_at: nil, updated_at: nil, little_class_id: nil, location_id: nil, session_series_token: nil>

我的LittleClassSession模型如下:

class LittleClassSession < ActiveRecord::Base
  belongs_to :little_class
  belongs_to :location
end

可能导致这种情况的原因是什么?最近我更改了application.rb中的默认时区,但我不明白为什么会出现这种情况。

2 个答案:

答案 0 :(得分:0)

您的:date_time字段为DateTime对象。

试试这个:

l.class_datetime = DateTime.now

而不是:

l.class_datetime = Time.now

答案 1 :(得分:0)

一旦我从application.rb删除了这两行,问题就消失了:

config.time_zone = 'Eastern Time (US & Canada)'
config.active_record.default_timezone = 'Eastern Time (US & Canada)'

这显然造成了一些混乱。