簡単な例:
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...