Ruby on Rails:updated_at - 在创建时设置为 0 [英] Ruby on Rails: updated_at - set as 0 on creation
问题描述
当我在 query
表上创建新记录时,我希望 updated_at
(时间戳)为 '0000-00-00 00:00:00' - 而不是当前时间戳,Ruby on Rails 默认设置.
When I create a new record on query
table, I want updated_at
(timestamp) to be '0000-00-00 00:00:00' - and not the current timestamp, as Ruby on Rails sets by default.
MySQL 字段:
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP
然而,Ruby on Rails 生成了这个 sql 查询:
However, Ruby on Rails generates this sql query:
INSERT INTO `queries` (`updated_at`) VALUES ('2011-01-04 17:40:15')
我该如何解决这个问题?
How do I fix this?
推荐答案
Rails 将 updated_at
设置为当前时间,因为这是最近更新记录的时间.它将更新视为一种创造.如果您想检查某些内容是否曾经更新过,请检查其 updated_at
和 created_at
是否相同.
Rails sets updated_at
to the current time because, well, thats when the record was most recently updated. It sees an update as a creation. If you want to check if something has ever been updated, check to see if its updated_at
and created_at
are the same.
否则,您应该能够通过在插入时强制属性来更改插入的值.
Otherwise, you should be able to change the value inserted by forcing the attribute upon insertion.
Post.new(@params.merge({:updated_at => DateTime::new})
或者,在模型的 before_create
方法中,设置 self.updated_at = DateTime::new
.
or, in a before_create
method on your model, set self.updated_at = DateTime::new
.
这篇关于Ruby on Rails:updated_at - 在创建时设置为 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!