Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

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 "5 years", so each of them is an interval by itself:

  def change
    create_table :times do |t|
      t.interval  :duration_min
      t.interval  :duration_max
      t.timestamps
    end
  end

but the DB migration fails when setting the data type to "interval" and rake returns:

undefined method 'interval' for #<ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::TableDefinition:0x007f8615694360> 

How do I define the table for it to accept (and understand) an input like "2 days"?

share|improve this question

1 Answer 1

up vote 5 down vote accepted

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">]>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.