在PostgreSQL和Ruby on Rails中使用间隔 [英] Using interval in PostgreSQL with Ruby on Rails

查看:56
本文介绍了在PostgreSQL和Ruby on Rails中使用间隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Rails应用程序中将持续时间(2天,5年等)保存为PostgreSQL中的时间间隔。

I want to save durations (2 days, 5 years, ...) as intervals in PostgreSQL from my Rails application.

duration_min和duration_max都是类似的值 2天或 5年,因此它们每个都是一个间隔:

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

,但将数据类型设置为 interval时,数据库迁移失败,并且瑞克返回:

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

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

如何定义表以接受(并理解) 2天之类的输入?

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

推荐答案

您已经关闭:

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

用法示例:

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">]>

这篇关于在PostgreSQL和Ruby on Rails中使用间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆