簡體   English   中英

Rails的update_all方法將錯誤的時間保存到MySQL DB中

[英]Wrong time is saved into MySQL DB by Rails' update_all method

我通過Rails將DateTime.now保存到MySQL DB的datetime列中,但是似乎保存了不正確的值。 保存的值過去了幾十秒。

我的代碼:

Rails.logger.info("Start: Calendars.where('user_id = ? and calendar_id = ?', @user.id, calendar_id)")

target = Calendars.where('user_id = ? and calendar_id = ?', @user.id, calendar_id)

Rails.logger.info("End: Calendars.where('user_id = ? and calendar_id = ?', @user.id, calendar_id)")

Rails.logger.info("last_clone_at update start")
now = DateTime.now
target.update_all(last_clone_at: now)

Rails.logger.info(now.strftime("%Y-%m-%dT%H:%M:%S")) # Output by DateTime.now
Rails.logger.info(target.first.last_clone_at) # Saved datetime value

日志輸出:

2014-06-09 14:39:03 INFO last_clone_at update start
2014-06-09 14:39:03 INFO 2014-06-09T14:39:03 # Output by DateTime.now
2014-06-09 14:39:03 INFO 2014-06-09 14:38:00 +0900 # Saved datetime value

我的日歷模型如下所示:

class Calendars < ActiveRecord::Base

  # Validations
  validates :user_id, presence: true
  validates :calendar_id, presence: true, uniqueness: { scope: :user_id }
end

我用:

  • Ruby 2.0
  • Rails 4.0.5
  • MySQL 5.5.37(來自Ubuntu 14.04存儲庫)

更新:日志輸出的其他示例:

2014-06-09 16:28:54 INFO last_clone_at update start
2014-06-09 16:28:54 INFO 2014-06-09T16:28:54
2014-06-09 16:28:54 INFO 2014-06-09 16:28:01 +0900

2014-06-09 16:28:55 INFO last_clone_at update start
2014-06-09 16:28:55 INFO 2014-06-09T16:28:55
2014-06-09 16:28:55 INFO 2014-06-09 16:28:02 +0900

2014-06-09 16:28:57 INFO last_clone_at update start
2014-06-09 16:28:57 INFO 2014-06-09T16:28:57
2014-06-09 16:28:57 INFO 2014-06-09 16:28:04 +0900

Update2:是時候執行Calendars.where(...)

2014-06-09 17:22:06 INFO開始:Calendars.where('user_id =?and calendar_id =?',@ user.id,calendar_id)2014-06-09 17:22:06 INFO結束:Calendars.where (“ user_id =?和calendar_id =?”,@ user.id,calendar_id)

我認為有可能。 對於數據庫, update_all可能是“繁重的”操作,並且需要一些時間來更新記錄(檢查日志)。

嘗試更改輸出:

Rails.logger.info(DateTime.now.strftime("%Y-%m-%dT%H:%M:%S"))
target.update_all(last_clone_at: DateTime.now)
Rails.logger.info(target.first.last_clone_at)`

我認為通過這種方式,您可以獲得更多的“更緊密”的價值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM