Rails Activerecord / Postgres时间格式(Rails Activerecord/Postgres time format)

18 IT屋

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"

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?

Thank you very much.


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).

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.

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.




 时间:" 2000-01-01 16:57:19"" 

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




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


本文地址:IT屋 » Rails Activerecord / Postgres时间格式