如何使用 Rails 在模型中存储时间长度?
我可以想到两种解决方案:
1)将小时,分钟,秒等存储在数据库中的单独列中
- 缺点:很多列
2)转换并存储秒数
- 我们仍然希望能够显示单独的字段小时、分钟、秒等形式。我们可以为每个属性编写虚拟属性,并编写一个 before_save 回调,将时间跨度转换为秒(尽管仍然很混乱)。
我是否错过了其他一些明显的解决方案?你们如何做到这一点?
I can think of two solutions:
1) Store hours, minutes, seconds, etc. in separate columns in the database
- Downside: a lot of columns
2) Convert and store the number of seconds
- We still want to be able to show seperate fields for hour, minute, second, etc. in the form. We could write virtual attribute for each of these and write a before_save callback that converts the timespan to seconds (still messy tho).
Am I missing some other obvious solution? How do you people do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我投票支持单列来跟踪持续时间。这使持续时间保持标准化,而您需要做几乎相同或更多的工作来标准化多列持续时间。
Rails (activesupport) 还为您提供了处理时间的绝佳方法。例如,如果您的持续时间以秒为单位,您可以轻松地将持续时间(以秒为单位)添加到某个时间点并获取结束时间:
结束时间 = Time.now + 持续时间(以秒为单位)
使用虚拟属性
将其分离出来需要更多的工作,但根据我的经验,这并不是更多的工作。也许有一个插件或 gem 可以简化它。
I vote for a single column to keep track of durations. That keeps the duration normalized, whereas you'll need to do almost as much work or more to normalize multi-column durations.
Rails (activesupport) also gives you wonderful methods to work with time. For example, if your duration is in seconds, you can easily add the duration in seconds to a point in time and get an end time:
end_time = Time.now + duration_in_secs
It is a bit more work using virtual attributes to separate it out, but in my experience, it's not that more work. perhaps there is a plugin or gem that simplifies it.
如果我通过表单上的 3 个字段接收输入,我更喜欢在数据库中拥有单独的列 - 它使事情变得更加干净和简单(毕竟,现在表中的一些额外列不必太担心)。那么您所需要的只是一个很好的方法来很好地输出内容。
I prefer to have separate columns in the database if I'm receiving the input via 3 fields on the form - it keeps things much cleaner and simpler (and after all, nowadays a few extra columns in a table isn't much to worry about). Then all you need is a nice method to output the stuff nicely.