3

私は最初の Rails アプリケーションに取り組んでいます。私は時間に少し立ち往生しています。私はレシピアプリケーションに取り組んでいます。2 つのフィールドを追加する必要があります。

  • 準備時間
  • 調理時間

2 つのうち、2 つのフィールドを追加して、食事の準備に必要な合計時間を計算したいと思います。

ロジックのない間違った方法でアプローチしました:(。基本的には2つのフィールドがあり、f.selectを使用して事前定義された時間を選択しました。しかし、そのアプローチの問題は、2つを追加するとグレゴリオ暦が無視されることですたとえば、40 分 + 50 分という形式は、1 時間 30 分ではなく 90 分になります。

コミュニティからの助けをいただければ幸いです。

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 に答える