【问题标题】:Rails 4. ActiveModel timezone convertedRails 4. ActiveModel 时区转换
【发布时间】:2013-12-02 01:55:20
【问题描述】:

我有一个 Rails 4.0.1 应用程序。某些原因我的查询采用错误的时区。我有以下查询:

puts '=====================', Time.zone.now
@headlines ||= Headline.includes(:admin, :cover).recent.where('published=? AND    publish_at<=?', true, Time.zone.now).limit(4)

输出如下所示:

=====================
2013-12-02 09:37:44 +0800
  Headline Load (1.3ms)  SELECT "contents".* FROM "contents" 
  WHERE "contents"."headline" = 't' 
  AND (published='t' 
  AND publish_at<='2013-12-02 01:37:44.941741') 
  ORDER BY "contents"."headline_position" 
  DESC LIMIT 4

如您所见,我的当前时间已在我的查询中转换。为什么?

【问题讨论】:

  • 有关 Rails 中时区的信息,请参阅我的博客文章 - jessehouse.com/blog/2013/11/15/… - 日期时间以 UTC 格式存储在数据库中。请注意这两个值是相同的 09:37:44 +0800 == 01:37:44

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


【解决方案1】:

http://railscasts.com/episodes/106-time-zones-revised 看看...它很短。

基本上...您可以在config/application.rb 文件中设置您的时区,如果它是静态的...您还需要在您的application_controller.rb 中设置一个around_filter 以在之前应用用户机器的时区采取任何行动(如果您有用户登录)。

class ApplicationController < ActionController::Base
  around_filter :user_time_zone, if: :current_user

private
  def user_time_zone(&block)
    Time.use_zone(current_user.location, &block)
  end
end

【讨论】:

  • 这在 Rails 4.1 中对你有用吗?我有相同的代码在 Rails 3.2 应用程序中工作,但它似乎不再在 Rails 4.1 中工作。不工作我的意思是在我看来我可以调用 Time.zone 并返回 UTC 而不是 user_time_zone 中设置的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-02
相关资源
最近更新 更多