Ruby on Rails: why ActiveRecord uses “datetime” type instead of “timestamp” for timestamp fields?

柔情痞子 提交于 2019-12-10 13:04:49

问题


In my database migration file I inserted the line:

t.timestamps

Two columns, as I expected, were created: "updated_at" and "created_at". However, their type is "datetime" and not "timestamp".

I am using MySQL and the "timestamp" type, as I understand, is designed exactly for such cases, as it uses less space and is independent of timezone.

So, is there any reason, why Rails 3 uses "datetime" and not "timestamp"? Should I try to fix that? If yes, is there any way to do this besides not using "t.timestamps" and defining "updated_at" and "created_at" columns separately every time for each new table?


回答1:


From memory, the mysql timestamp column type behaves similar to updated_at in that it is updated with the current time whenever the record is updated.

While this is useful for the updated_at column, this is not the desired behaviour for created_at.

In addition, Rails handles the timezone as specified in your app's settings (should would normally be set to UTC), so using mysql's time may be inconsistent with other datetime records.




回答2:


timestamp columns have a limited range which begins in 1970 and ends in 2038. You can google "Unix Millennium Bug" for more information, but it's basically because unix timestamps are stored as a 32-bit signed integer. A timestamp is expressed in seconds since Jan. 1, 1970, and the number wraps on itself in 2038. For this reason, I typically use datetime even when timestamp seems like an easier solution, especially to represent historical or forecasted data further off into the past or future.



来源:https://stackoverflow.com/questions/5053897/ruby-on-rails-why-activerecord-uses-datetime-type-instead-of-timestamp-for

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