Rails 5 and PostgreSQL 'Interval' data type

activerecord, postgresql, ruby-on-rails

Solution

From Rails 5.1, you can use postgres 'Interval' Data Type, so you can do things like this in a migration:

add_column :your_table, :new_column, :interval, default: "2 weeks"

Although ActiveRecord only treat interval as string, but if you set the `IntervalStyle` to `iso_8601` in your postgresql database, it will display the interval in iso8601 style: `2 weeks => P14D`

execute "ALTER DATABASE your_database SET IntervalStyle = 'iso_8601'"

You can then directly parse the column to a `ActiveSupport::Duration`

In your `model.rb`

def new_column
  ActiveSupport::Duration.parse self[:new_column]
end

More infomation of ISO8601 intervals can be find at https://en.wikipedia.org/wiki/ISO_8601#Time_intervals

Problem

Does Rails really not properly support PostgreSQL's interval data type? I had to use this Stack Overflow answer from 2013 to create an interval column, and now it looks like I'll need to use this piece of code from 2013 to get ActiveRecord to treat the interval as something other than a string. Is that how it is? Am I better off just using an integer data type to represent the number of minutes instead?

Original source

Related problems