Using interval in PostgreSQL with Ruby on Rails

后端 未结 2 765
孤城傲影
孤城傲影 2021-02-14 16:47

I want to save durations (2 days, 5 years, ...) as intervals in PostgreSQL from my Rails application.

Both duration_min and duration_max are values like \"2 days\" or \"

2条回答
  •  我在风中等你
    2021-02-14 17:20

    You were close:

    class CreateExamples < ActiveRecord::Migration
      def change
        create_table :examples do |t|
          t.column :duration_min, :interval
          t.column :duration_max, :interval
          t.timestamps
        end
      end
    end
    

    Usage example:

    Example.create duration_min: '2 hours', duration_max: '2 days'
    #=> #
    Example.where(%[TIMESTAMP ? - TIMESTAMP ? BETWEEN "duration_min" AND "duration_max"], DateTime.now, 10.hours.ago)
    #=> #]>
    

提交回复
热议问题