Using interval in PostgreSQL with Ruby on Rails

后端 未结 2 1412
忘掉有多难
忘掉有多难 2021-02-14 16:54

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:10

    We have an implementation of interval for Rails 5.1 that you can try.

    https://gist.github.com/vollnhals/a7d2ce1c077ae2289056afdf7bba094a

    0 讨论(0)
  • 2021-02-14 17:19

    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 id: 1, duration_min: "2 hours", duration_max: "2 days", created_at: "2013-12-02 14:20:36", updated_at: "2013-12-02 14:20:36">
    Example.where(%[TIMESTAMP ? - TIMESTAMP ? BETWEEN "duration_min" AND "duration_max"], DateTime.now, 10.hours.ago)
    #=> #<ActiveRecord::Relation [#<Example id: 1, duration_min: "02:00:00", duration_max: "2 days", created_at: "2013-12-02 14:20:36", updated_at: "2013-12-02 14:20:36">]>
    
    0 讨论(0)
提交回复
热议问题