2017-07-14 3 views
0

私はこのようなコードを持っていた:なぜActiveRecord :: Calculations.maximumは、ActiveSupport :: TimeWithZoneの代わりにTImeオブジェクトを返しますか?

Foo.order(:posted_at).last.posted_at 

を、私はそれを書くためのより良い方法を学びました。別の方法はActiveSupport::TimeWithZone返し、私の知る限りではRailsは基本的にTimeWithZoneを返しながら

Foo.maximum(:posted_at) 

は、しかし、私は maximum戻り Timeオブジェクトに気づきました。なぜ maximumが通常の Timeオブジェクトを返しますか?

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

これは 'activerecord'の問題です:モデルのインスタンス化と計算(max、sumなど)は異なる方法になります。 Modelインスタンスは 'ActiveSupport :: TimeWithZone'にキャストしますが、計算コードはモデルコードと交差せず、キャストは行いません –

+0

ありがとう!コメントを回答として投稿すると、私はそれを受け入れます。 – ironsand

答えて

0

これは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など)implementationmodel 1と交差しないと、このような鋳造を行いません。

関連する問題