Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
650 views
in Technique[技术] by (71.8m points)

activerecord - Ruby on Rails: updated_at - set as 0 on creation

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 field:

`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

or, in a before_create method on your model, set self.updated_at = DateTime::new.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...