【问题标题】:Why ActiveRecord::Calculations.maximum return TIme object instead of ActiveSupport::TimeWithZone?为什么 ActiveRecord::Calculations.maximum 返回 TIme 对象而不是 ActiveSupport::TimeWithZone?
【发布时间】:2017-12-19 14:25:07
【问题描述】:

我有这样的代码:

Foo.order(:posted_at).last.posted_at

我学会了更好的写作方法。

Foo.maximum(:posted_at)

但我注意到maximum 返回Time 对象,而另一种方式返回ActiveSupport::TimeWithZone,据我所知Rails 基本上返回TimeWithZone。为什么maximum 返回正常的Time 对象?

Foo.maximum(:posted_at).class
# Time < Object
Foo.order(:posted_at).last.posted_at.class
# ActiveSupport::TimeWithZone < Object

【问题讨论】:

  • 这是activerecord 问题:模型实例化和计算(最大值、总和等)采用不同的方式。模型实例确实转换为ActiveSupport::TimeWithZone,而计算代码不与模型代码相交并且不进行转换
  • 我明白了,谢谢!如果您将评论作为答案发布,我会接受。

标签: ruby-on-rails time activesupport


【解决方案1】:

这是Activerecord 问题。转换为 ActiveSupport::TimeWithZone 是在 model 级别上实现的。在控制台中尝试:

model_instance = MyModel.new
t = Time.now # not Time.current
model_instance.created_at.class
t.class # Time
model_instance.created_at = t
model_instance.created_at.class # ActiveSupport::TimeWithZone

maximumcountsum 等)implementation 不与 model 相交,并且不进行此类转换。

【讨论】:

    猜你喜欢
    • 2022-08-12
    • 2011-11-22
    • 1970-01-01
    • 2012-10-08
    • 1970-01-01
    • 2011-10-19
    • 2011-10-06
    • 2012-04-23
    • 1970-01-01
    相关资源
    最近更新 更多