0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

whereで複数条件でカラムを合計する

Posted at

現在作っているダイエットのためのカロリー計算アプリですが、
トップページの本日食べた栄養素とカロリー合計を表示するようにしています。
集計するには
user_id別
カロリー別
同一日付内で合計しています

■id別日付別という2重条件についての処理

.where(×××××: day).where(×××××: current_user.id)     ※:カラム名

■合計します

.sum(:×××××)     ※:カラム名

■小数点以下の計算が多いので小数点3桁以下を四捨五入

.round(3)

でき上がったのは以下

[circle_contoroller.rb]
     @calorie = CookedFood.where(meal_date: day).where(user_id: current_user.id).sum(:calorie).round(3)
     @protein = CookedFood.where(meal_date: day).where(user_id: current_user.id).sum(:protein).round(3)
     @carbohydrate = CookedFood.where(meal_date: day).where(user_id: current_user.id).sum(:carbohydrate).round(3)
     @sugar_content = CookedFood.where(meal_date: day).where(user_id: current_user.id).sum(:sugar_content).round(3)
     @fiber = CookedFood.where(meal_date: day).where(user_id: current_user.id).sum(:fiber).round(3)
     @salt = CookedFood.where(meal_date: day).where(user_id: current_user.id).sum(:salt).round(3)
     @lipid = CookedFood.where(meal_date: day).where(user_id: current_user.id).sum(:lipid).round(3)
     @meal_quantity = CookedFood.where(meal_date: day).where(user_id: current_user.id).sum(:meal_quantity)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?