Ben*_*min 3 ruby ruby-on-rails timer recipe form-helpers
我正在研究我的第一个Rails应用程序.我有点卡住了时间.我正在研究食谱应用程序.我需要添加两个字段.
在这两个中,我想添加两个字段来计算准备餐点所需的总时间.
我接近它错误的方式,没有逻辑:(.基本上我有两个字段,我使用f.select选择预定义的时间.但我的方法的问题是,当添加两个,它忽略了格里高利格式例如40分钟+ 50分钟将变为90分钟而不是1小时30分钟.
我很感激社区的帮助.
一个简单的例子:
prep_time = 40.minutes
cook_time = 50.minutes
total_time = prep_time + cook_time
formatted_total_time = Time.at(total_time).gmtime.strftime('%I:%M')
# outputs 01:30 which is HOURS:MINUTES format
Run Code Online (Sandbox Code Playgroud)
如果你想要90分钟代替:
formatted_total_time = total_time / 60
# outputs 90
Run Code Online (Sandbox Code Playgroud)
更新:
把它放在与你正在使用它的任何视图相关联的辅助文件中(即app/helpers/recipes_helper.rb)
module RecipesHelper
def convert_to_gregorian_time(prep_time, cook_time)
# returns as 90 mins instead of 1hr30mins
return (prep_time + cook_time) / 60
end
end
Run Code Online (Sandbox Code Playgroud)
然后你只需在你的视图中调用它(app/views/recipes/show.html.haml例如:
# Note: this is HAML code... but ERB should be similar
%p.cooking_time
= convert_to_gregorian_time(@recipe.prep_time, @recipe.cook_time)
Run Code Online (Sandbox Code Playgroud)
如果您将数据库中的时间存储为整数(您应该这样做),那么您可以这样做:
%p.cooking_time
= convert_to_gregorian_time(@recipe.prep_time.minutes, @recipe.cook_time.minutes)
Run Code Online (Sandbox Code Playgroud)
where @recipe.prep_time是一个值为40 @recipe.cook_time的整数,是一个值为50的整数
并且您的数据库架构看起来像:
# == Schema Information
#
# Table name: recipes
#
# id :integer not null, primary key
# prep_time :integer
# cook_time :integer
# # other fields in the model...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1134 次 |
| 最近记录: |