Using the Postgres interval data type

0

rails generate model Availability
class CreateAvailabilities < ActiveRecord::Migration[6.0]
  def change
    reversible do |dir|
      dir.up do
        execute "ALTER DATABASE \"#{connection.current_database}\" SET intervalstyle = 'iso_8601'"
      end
      dir.down do
        execute "ALTER DATABASE \"#{connection.current_database}\" SET intervalstyle = 'postgres'"
      end
    end

    create_table :availabilities do |t|
      t.references :user,      null: false, foreign_key: true
      t.datetime   :starts_at, null: false
      t.interval   :duration,  null: false
      t.text       :schedule
      t.datetime   :ends_at
      t.timestamps             null: false
    end
  end
end
Availability.rb
class Availability < ApplicationRecord
  attribute :duration, :duration 
  belongs_to :user
end
config/initializers/duration_type.rb
class DurationType < ActiveRecord::Type::String
  def cast(value)
    return value if value.blank? || value.is_a?(ActiveSupport::Duration)
    ActiveSupport::Duration.parse(value)
  end

  def serialize(duration)
    duration ? duration.iso8601 : nil
  end
end

ActiveRecord::Type.register(:duration, DurationType)

https://thoughtbot.com/blog/recurring-events-and-postgresql

  • 0 posts
  • 1 subtopic
  • 7 months ago by vince