Rails: why time datatype start at 1/1/2000

会有一股神秘感。 提交于 2019-12-12 01:59:08

问题


I have a column that I only want to store time (hour, minute, second). for example here is one migration:

add_column :products, :start_hour, :time

When I insert to database start_hour always start with 1/1/2000 for example: 2000-01-01 01:19:00 +0700. Please explain for me why.


回答1:


There is no time-of-day class in Ruby or Rails so ActiveRecord represents time columns with datetime/timestamp classes.

If you look inside the database without any of the ActiveRecord, Rails, or Ruby noise in the way, you'll see an HH:MM:SS time-of-day value. But when ActiveRecord pulls a time out of the database, it sets the date component to 2000-01-01 because a datetime has to have a date and AR picks that one.

Any time you work with a start_hour in Ruby you'll have to ignore the date component.




回答2:


The difference between formats stored in your DB have nothing to do with Rails and everything to do with your database. Date or Time formats are only 'valid' within your application, not within the database -more simply they are only responsible for the way time objects are displayed to your users and will not affect the way data is stored. Your best bet is to save the records as time objects and then use rails helpers to present the data to your users in a meaningful way with such methods as strptime etc.



来源:https://stackoverflow.com/questions/42538468/rails-why-time-datatype-start-at-1-1-2000

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