Rails Activerecord/Postgres时间格式

编程入门 行业动态 更新时间:2024-10-24 01:55:47
本文介绍了Rails Activerecord/Postgres时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用Postgres数据库进行Rails项目.对于我的一个模型,我有一个时间列,称为(巧妙地)时间.创建模型时,我将此列的数据类型设置为时间",(可能不正确)理解该数据类型仅用于存储时间,而没有日期.

I am working on a Rails project using a Postgres database. For one of my models, I have a time column, called (cleverly) time. When I created the model, I set the data type for this column as 'time', with the (perhaps incorrect) understanding that this data type was for storing time only, no date.

t.time :time

但是,当我向模型提交数据时,时间是正确的,但以不正确的日期为前缀:

However, when I submit data to the model, the time is correct but prefixed by an incorrect date:

time: "2000-01-01 16:57:19"

我只希望该列存储时间(例如'16:57:19'). 时间"是否是要使用的正确数据类型?还是有其他方法可以解决这个问题?

I just want the column to store the time (like '16:57:19'). Is 'time' the correct data type to use? Or is there some other way I should handle this problem?

非常感谢您.

推荐答案

问题是Ruby或Rails中没有时段.所有时间类别都是日期或时间戳(即日期加上一天中的时间).

The problem is that there is no time-of-day class in Ruby or Rails. All the time classes are dates or timestamps (i.e. date plus time of day).

在数据库内部,它将是 time (无时区)列,它将在数据库内部正常运行.但是,一旦时间进入Ruby,ActiveRecord将添加一个日期组件,因为没有可用的普通时间类,因此恰好使用2000-01-01作为日期.

Inside the database it will be a time (without timezone) column and it will behave properly inside the database. However, once the time gets into Ruby, ActiveRecord will add a date component because there is no plain time-of-day class available, it just happens to use 2000-01-01 as the date.

在数据库内部一切都会好起来的,但是当您不在Rails的数据库外部时,您必须格外小心,以忽略日期部分.

Everything will be fine inside the database but you'll have to exercise a little bit of caution to ignore the date component when you're outside the database in Rails.

更多推荐

Rails Activerecord/Postgres时间格式

本文发布于:2023-10-17 10:34:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1500663.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:格式   时间   Rails   Activerecord   Postgres

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!