💎Rails tip: Interval column type

Sebastien Auriault
Feb 5, 2022
Did you know that since Rails 6.1, you can easily add a column of type interval if you use Postgres? This can be convenient if you have for example a model for recurring events with a specific duration like 5 days.

class CreateEvents < ActiveRecord::Migration[6.1]
  def change
    create_table :events do |t|
      t.string :name
      t.interval :duration

      t.timestamps
    end
  end
end

2 comments

Sahil Grover
Feb 6, 2022
I would love to see how does it work different than `integer` or what is the advantage over using integer ?

Also, does it create the same `integer` type in postgres ?
Sebastien Auriault
Feb 6, 2022
Interval is a Postgres type, which Rails turn into an instance of ActiveSupport::Duration when reading the attribute. You can set the attribute like this: ‘event.update(duration: 5.days)’ which can be convenient when you want to store a duration like how long something lasts without knowing the start time. Yes you could use an integer to store the number of seconds but then if you wanna use ActiveSupport duration to do things like 5.days - 1.hour you will need to convert it yourself. Also I believe Postgres can do some neat things with interval column type.