Rails 5和PostgreSQL'Interval'数据类型 [英] Rails 5 and PostgreSQL 'Interval' data type

查看:103
本文介绍了Rails 5和PostgreSQL'Interval'数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rails真的不正确地支持PostgreSQL的interval数据类型吗?

Does Rails really not properly support PostgreSQL's interval data type?

我不得不使用来创建一个间隔列,现在看来我需要使用这段代码自2013年开始,让ActiveRecord将间隔视为字符串以外的其他内容。

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?

推荐答案

在Rails 5.1中,您可以使用postgres'Interval'数据类型,因此您可以在迁移中执行以下操作:

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"

尽管ActiveRecord仅将时间间隔视为字符串,但是如果您将在您的Postgresql数据库中 IntervalStyle iso_8601 ,它将以iso8601样式显示间隔: 2周=> P14D

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

然后您可以直接将列解析为 ActiveSupport :: Duration

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

在您的 model.rb

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

有关ISO8601间隔的更多信息,请参见 https:// en。 wikipedia.org/wiki/ISO_8601#Time_intervals

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

这篇关于Rails 5和PostgreSQL'Interval'数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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