3

我正在开发我的第一个 Rails 应用程序。我有点被时间困住了。我正在开发一个食谱应用程序。我需要添加两个字段。

  • 准备时间
  • 烹饪时间

在这两个字段中,我想将这两个字段相加以得出准备餐点所需的总时间。

我以错误的方式接近它没有逻辑:(。基本上我有两个字段,我使用 f.select 来选择预定义的时间。但我用这种方法遇到的问题是,当添加这两个时,它忽略了公历格式,例如 40 分钟 + 50 分钟将变为 90 分钟而不是 1 小时 30。

我会感谢社区的任何帮助。

4

1 回答 1

6

一个简单的例子:

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

如果您想要 90 分钟:

formatted_total_time = total_time / 60

# outputs 90

更新:

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

然后你只需在你的视图中调用它(即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)

如果您将数据库中的时间存储为整数(您应该这样做),那么您可以这样做:

%p.cooking_time
  = convert_to_gregorian_time(@recipe.prep_time.minutes, @recipe.cook_time.minutes)

其中@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...
于 2011-08-09T19:11:27.253 回答