私は同様の問題があり、ActiveRecordモデルの特定の列に対してリーダーメソッドを定義することになりました。このように:
class DivingResults < ActiveRecord::Base
# This overrides the same method for db column, generated by rails
def underwater_duration
interval_from_db = super
time_parts = interval_from_db.split(':')
if time_parts.size > 1 # Handle formats like 17:04:41.478432
units = %i(hours minutes seconds)
in_seconds = time_parts
.map.with_index { |t,i| t.to_i.public_send(units[i]) }
.reduce(&:+) # Turn each part to seconds and then sum
ActiveSupport::Duration.build in_seconds
else # Handle formats in seconds
ActiveSupport::Duration.build(interval_from_db.to_i)
end
end
end
これにより、別の場所でActiveSupport::Duration
インスタンスを使用できます。近い将来、Railsは自動的にPostgreSQLのインターバルデータ型の処理を開始することを願っています。
[適切な](https://github.com/rails/rails/blob/v5.1.1/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb#L112)の「間隔」は、 [places](https://github.com/rails/rails/blob/v5.1.1/activerecord/lib/active_record/connection_adapters/postgresql/schema_definitions.rb#L91)ですので、Rails5のように見えます。私は答えてもらえますが、Rails5のセットアップを簡単にして推測を検証する必要はなく、サポートがどれだけ広がっているのか分かりません(実際にあれば)。 –
ありがとうございます。 'interval'のものがかなり最近追加されたようですので、5.1.1にアップグレードしてよりうまく動作するかどうかを確認します。 –
アップグレードのように、最初の問題(簡単に間隔列を作成できるようになります)が修正されません(列を文字列ではなく間隔として解釈することがアクティブレコードにあります)。整数型のデータ型を使う方が簡単かもしれないと思います。助けてくれてありがとう。 –