Rails Activerecord/Postgres time format

有些话、适合烂在心里 提交于 2020-08-27 05:56:39

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/34978905/rails-activerecord-postgres-time-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!