在Rails模型中使用工期字段 [英] Using a duration field in a Rails model
本文介绍了在Rails模型中使用工期字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找在Rails模型中使用工期字段的最佳方法。我希望格式为HH:MM:SS(例如:01:30:23)。正在使用的数据库在本地是sqlite,在生产中是Postgres。
I'm looking for the best way to use a duration field in a Rails model. I would like the format to be HH:MM:SS (ex: 01:30:23). The database in use is sqlite locally and Postgres in production.
我也想使用该字段,因此我可以查看该字段中的所有对象,并得出该对象中所有对象的总时间并最终得到类似的结果:
I would also like to work with this field so I can take a look at all of the objects in the field and come up with the total time of all objects in that model and end up with something like:
30条记录,总计45小时25分钟34秒。
30 records totaling 45 hours, 25 minutes, and 34 seconds.
那么最适合什么呢?
- 迁移的字段类型
- CRUD表单的表格字段(小时,分钟,第二个下拉菜单?)
- 最便宜的方法,用于生成CRUD表单中所有记录的总持续时间模型
推荐答案
- 以整数形式存储在数据库中(数字
- 您的输入表单将取决于确切的用例。下拉菜单很痛苦;最好使用小时数,分钟数和秒数的持续时间较小的文本字段。
- 只需在持续时间列上运行
SUM
查询以生成总计。如果使用整数,则简单又快速。 - Store as integers in your database (number of seconds, probably).
- Your entry form will depend on the exact use case. Dropdowns are painful; better to use small text fields for duration in hours + minutes + seconds.
- Simply run a
SUM
query over the duration column to produce a grand total. If you use integers, this is easy and fast. - 使用助手在视图中显示持续时间。您可以使用
123.seconds
(替换<$$)轻松地将持续时间(以秒为整数)转换为ActiveSupport :: Duration
c $ c> 123 和数据库中的整数)。在生成的持续时间
上使用检查
进行格式化。 (这不是完美的。您可能想自己写点东西。) - 在模型中,您可能希望属性读取器和写入器返回/获取
ActiveSupport :: Duration
对象,而不是整数。只需定义duration =(new_duration)
和duration
,它们在内部调用read_attribute
/write_attribute
带整数参数。 - Use a helper to display the duration in your views. You can easily convert a duration as integer of seconds to
ActiveSupport::Duration
by using123.seconds
(replace123
with the integer from the database). Useinspect
on the resultingDuration
for nice formatting. (It is not perfect. You may want to write something yourself.) - In your model, you'll probably want attribute readers and writers that return/take
ActiveSupport::Duration
objects, rather than integers. Simply defineduration=(new_duration)
andduration
, which internally callread_attribute
/write_attribute
with integer arguments.
另外:
这篇关于在Rails模型中使用工期字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文