[英]How to pass a variable parameter value using the update_all() method in Rails?
[英]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
我用:
更新:日志输出的其他示例:
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.