定义哪些模型将转换为activerecord timezone配置

And*_*rao 2 timezone ruby-on-rails ruby-on-rails-3

我正在寻找一种仅在某些模型中使用ActiveRecord时区配置的方法,或者在某些我不需要的方法中禁用它的方法.

像这样的东西:

模型User,Access,Sale使用与application.rb相同的时区:config.time_zone ="xxxx"

但模型Lap,CheckIn不使用时区设置或UTC.

我想过使用一个after_initialize方法来清除time_zone配置,比如*after_free*(我知道它不存在)从旧的配置值中支持时区设置.

这不是一个简单的方法吗?

jwa*_*ack 6

如果您正在寻找这样做在一个特定的模式,或在特定模型的特定字段中所描述的方法这个职位的工作很适合我.

# Turn it off for just some columns
class Picture < ActiveRecord::Base
 def self.skip_time_zone_conversion_for_attributes
   [:created_at, :published_at]
 end
end

# Turn it off for the whole model
class Picture < ActiveRecord::Base
  def self.time_zone_aware_attributes
    false
  end
end
Run Code Online (Sandbox Code Playgroud)

如果它有帮助,这是我的测试用例:

before :all do
  @current_tz = Time.zone
  # Test usually runs in UTC; test this as if in production, per config/application.rb
  Time.zone = 'Pacific Time (US & Canada)'
end

after :all do
  Time.zone = @current_tz
end

it 'should report UTC time as UTC time' do
  new_obj = MyModel.create(start_time: DateTime.new(2013, 3, 31, 0, 0, 0, 0))
  new_obj.reload
  new_obj.start_time.to_s.should == 'Sun, 31 Mar 2013 00:00:00 +0000'
end
Run Code Online (Sandbox Code Playgroud)