向大家致以问候。我目前正在阅读Ruby on Rails教程的第11章。目前我正试图让Time.zone.now工作。
在控制台上,当我输入Time.zone.now
时,一切正常2.4.0 :007 > Time.zone.now
=> Fri, 23 Jun 2017 22:34:33 UTC +00:00
class AccountActivationsController < ApplicationController
def edit
user = User.find_by(email: params[:email])
if user && !user.activated? && user.authenticated?(:activation, params[:id])
# (1) time set to a variable
time = Time.zone.now
user.update_attribute(:activated, true)
# (2) This time variable results to year 2000
user.update_attribute(:activated_at, time)
log_in user
# (3) This time variable results to year 2017
flash[:success] = "Account activated! #{time}"
redirect_to user
else
flash[:danger] = "Invalid activation link"
redirect_to root_url
end
end
end
当我在rails控制台上输入User.last时,以下是输出
=> #<User id: 110, name: "foo", email: "foo@email.com", created_at: "2017-06-23 22:28:09", updated_at: "2017-06-23 22:28:21",...., activated: true, activated_at: "2000-01-01 22:28:21">
2.4.0 :009 >
如您所见,activated_at显示正确的时间,但没有显示正确的年,日和月。 但是,相同的时间变量用作上面注释为注释(3)的闪存消息。
result form: flash[:success] = "Account activated! #{time}" (comment 2)
有什么想法吗?
所有我能够尝试的是config / application.rb
中的以下配置的混合require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module SampleApp
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
config.active_record.time_zone_aware_types = [:datetime, :time]
# config.active_record.time_zone_aware_types = [:datetime]
config.active_record.default_timezone = :local
end
end
答案 0 :(得分:1)
这听起来像是数据库中列类型的问题。我不确定您使用的是哪个数据库,但是在数据库列类型为time
而不是datetime
之前我已经看到了这一点。
检查您的db/schema.rb
或db/structure.sql
并确认activated_at
列的类型。
幕后花絮和mysql存储时间戳值为2000-01-01午夜之前或之后的秒数。