[英]Sum of attributes in model with has_many :through association not working in Rails 5
[英]How to get attributes of model in has_many :through association in Rails 5
所以我在has_many:through关联中有2个模型。 两种模式是餐食和食物。 基本上,一顿饭可以有多种食物,而一种食物可以成为很多餐的一部分。 第三个连接模型称为餐食。 我已经设置好了,这样当您创建新餐时,您可以通过复选框选择餐点中的所有食品。 食品具有诸如卡路里和蛋白质的属性,而膳食具有诸如total_calories和total_proteins的属性。 如何制作新餐时可以计算所有食品的所有属性(卡路里,蛋白质等)的值?
到目前为止,这是我的代码:
楷模
class Meal < ApplicationRecord
belongs_to :user, optional: true
has_many :meal_foods
has_many :foods, through: :meal_foods
end
class Food < ApplicationRecord
has_many :meal_foods
has_many :meals, through: :meal_foods
end
class MealFood < ApplicationRecord
belongs_to :meal
belongs_to :food
end
膳食管理员
def create
@meal = Meal.new(meal_params)
@meal.user_id = current_user.id
@meal.total_calories = #Implement code here...
if @meal.save
redirect_to @meal
else
redirect_to root_path
end
end
用餐视图(创建操作)
<%= form_for(@meal) do |f| %>
<div class="field">
<%= f.label :meal_type %>
<%= f.select :meal_type, ["Breakfast", "Lunch", "Dinner", "Morning Snack", "Afternoon Snack, Evening Snack"] %>
</div>
<div class="field">
<% Food.all.each do |food| %>
<%= check_box_tag "meal[food_ids][]", food.id %>
<%= food.name %>
<% end %>
</div>
<div class="field">
<%= f.submit class: "button button-highlight button-block" %>
</div>
<% end %>
提前致谢!
您可以将sum
例如用于卡路里:
class Meal < ApplicationRecord
belongs_to :user, optional: true
has_many :meal_foods
has_many :foods, through: :meal_foods
def total_calories
foods.sum(:calories)
end
end
Sum适用于关联中的任何数字列。
如果对于某些人而言,您需要将该值存储在数据库中(例如,您将根据热量含量对餐点进行排序,并且更容易存储该值),那么您可以告诉餐点,当它被创建时,它应该计算并存储卡路里,例如:
class Meal < ApplicationRecord
belongs_to :user, optional: true
has_many :meal_foods
has_many :foods, through: :meal_foods
# Tells rails to run this method when each Meal is first created
after_create :store_total_calories
# actually calculates the number of calories for any given meal (can be used even after saving in the db eg if the calories changed)
def calculate_total_calories
foods.sum(:calories)
end
# calculates, then resaves the updated value
def store_total_calories
update(total_calories: calculate_total_calories)
end
end
注意:有关after_create
回调的更多信息,请after_create
此处
注意:对于所有Just Work,在控制器中无需执行任何操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.