2016-08-28 8 views
0

次のクエリは異なる結果をもたらし、両方の結果が2である必要があります。私は私のdb(postgres)でtimestampカラムを使用していて、end_atカラムが与えられたUNIXタイムスタンプ以下のオブジェクトを探しています。UNIXのタイムスタンプを検索すると異なる結果が表示される

私はいくつかのデータをシードした場合、クエリで使用されるタイムスタンプは、例えば、あるかもしれない
puts object.time_records.where('time_records.end_at <= ?', object.time_records.second.end_at).count #=> 2 (Correct) 
puts object.time_records.where('time_records.end_at <= ?', DateTime.strptime(object.time_records.second.end_at.to_i.to_s, '%s')).count # => 1 (Incorrect) 
puts object.time_records.where('time_records.end_at <= ?', Time.at(object.time_records.second.end_at.to_i)).count # => 1 (Incorrect) 

1473024092 

その後、私はオブジェクトのタイムスタンプを印刷する場合:

puts object.time_records.pluck(:end_at).map(&:to_i) 

私は以下の結果が得られます。

1472419292 
1473024092 
1473628892 
1474233692 

これらからわかるように、正しい結果は2でなければなりません。誰かが似たようなものに遭遇した場合、私は正しい方向にポインタを感謝します。

これは価値がありますが、これは私が宝石のために書いている仕様で起こっています。私は、解析とタイムスタンプに変換するためのin_time_zone.utcのさまざまな組み合わせを試みました。それらはすべて同じ結果を提供します。 to_sが両方とも等しい場合、タイムスタンプに変換してTimeに戻って均等性をテストするとfalseになります。

私はIRBの例を実行しました:

2.3.0 :001 > now = Time.now 
=> 2016-08-28 21:58:43 +0100 
2.3.0 :002 > timestamp = now.to_i 
=> 1472417923 
2.3.0 :003 > parsed_timestamp = Time.at(timestamp) 
=> 2016-08-28 21:58:43 +0100 
2.3.0 :004 > now.eql?(parsed_timestamp) 
=> false 
2.3.0 :005 > now == parsed_timestamp 
=> false 
2.3.0 :006 > now === parsed_timestamp 
=> false 
2.3.0 :007 > now.class 
=> Time 
2.3.0 :008 > parsed_timestamp.class 
=> Time 
+2

あなたのDBは、分数倍を処理していますか? –

+1

my.custom.activerecord.query.to_sqlを使用して、実際に実行されているSQLクエリが何であるかを調べることができます。 – Bustikiller

+0

@FrederickCheungこれは問題ありませんでした。 – michaeldever

答えて

1

問題は、分数倍でした。 UNIXのタイムスタンプは2番目の時刻になるため、to_iを変換すると、ミリ秒は破棄されます。タイムスタンプ・カラムの精度を設定する

は、この問題を解決:

class CreateTimeRecords < ActiveRecord::Migration 
    def change 
    create_table :time_records do |t| 
     t.belongs_to :object, index: true, null: false 

     t.datetime :start_at, null: false, index: true, precision: 0 
     t.datetime :end_at, null: false, index: true, precision: 0 

     t.timestamps null: false 
    end 
    end 
end 
関連する問題