覆盖 Rails Updated_at 属性
我想修改 updated_at 属性,以便每次更新记录时,它只会显示日期和小时,而小时和分钟为零。 不再是 2010-08-13 11:04:12,而是 2010-08-13 11:00:00。在 Rails 2.3 中执行此操作最合理的方法是什么?
更新
我想做我所要求的事情的原因是因为我想按日期对数据进行排序,省略小时和秒。
谢谢!
I would like to modify updated_at attribute so that every time record is updated it would only show date and hours while hours and minutes being zeros. Instead of 2010-08-13 11:04:12, there would be 2010-08-13 11:00:00. What is the most rational way to do this in Rails 2.3?
Update
The reason why I want to do what I have asked is because I would like to sort data, by date with hours and seconds omitted.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不要尝试更改数据库中存储的值;更改输出方式:
请参阅
strftime
< /a> ruby doc 用于您可以使用的其他格式说明符。根据您的更新,我仍然不会更改
updated_at
的存储方式,而是在查询的ORDER BY
中格式化日期。例如,您可以对我的应用程序中的实时表进行非常快速的分析测试,该表包含大约 22,000 条记录。
ORDER BY Updated_at
需要 2.94 到 3.19 秒才能完成,平均时间为 3.00 秒。ORDER BY DATE(updated_at), HOUR(updated_at)
需要 2.93 到 3.06 秒才能完成,平均时间为 2.99 秒。这是分析数据:Don't try to change the value stored in the database; change how you are outputting it:
See the
strftime
ruby doc for other format specifiers you can use.Based on your update, I would still not change how
updated_at
is stored, but instead format the date within theORDER BY
of your query. For instance, you couldI did a very quick profiling test on a live table in my application, which has about 22,000 records.
ORDER BY updated_at
took between 2.94 and 3.19s to complete, with a mean time of 3.00s.ORDER BY DATE(updated_at), HOUR(updated_at)
took between 2.93 and 3.06s to complete, with a mean time of 2.99s. Here's the profiling data:它是一个时间戳对象,因此您最好只使用辅助函数来截断分/秒信息。
It's a time stamp object so your probably best off just to use a helper function to truncate the min/sec info.
whatever.created_at.strftime("%Y-%m-%d %H:00:00")
whatever.created_at.strftime("%Y-%m-%d %H:00:00")
我会推荐丹尼尔的解决方案。但是,如果您100%肯定想要使用修改后的“updated_at”字段保存记录,则必须为给定模型重新实现rails的自动时间戳。
因此,在您的模型中,您可以执行以下操作:
I would recommend Daniel's solution. However, if you're 100% positive that you want to save the record with your modified "updated_at" field, you'll have to re-implement rails' auto-timestamping for the given model.
So, in your model, you can do the following:
这不是您应该对活动记录执行的操作。这是视图助手可以完成的事情,并且您不需要改变保存内容的方式,这可能只是将来更多的工作。
考虑一下
strftime
以及如何改变它。在帮助文件中:
This isn't something you should do with active record. It's something that a view helper could accomplish and you don't need to alter the way things are getting saved which will probably just be more work in the future.
Think about
strftime
and how you can alter that instead.In a helper file: