【发布时间】:2018-03-02 02:34:07
【问题描述】:
所以我在 has_many :through 关联中有 2 个模型。这两个模型是膳食和食物。基本上,一顿饭可以有多个食物,一个食物可以是多餐的一部分。第三个连接模型称为meal_foods。 我进行了设置,这样当您创建新餐点时,您可以通过复选框选择餐点的所有食物。食品具有卡路里和蛋白质等属性,而膳食具有总卡路里和总蛋白质等属性。 我如何才能在制作新餐点时计算所有食物的所有属性(卡路里、蛋白质等)的值?
到目前为止,这是我的代码:
模型
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 %>
谢谢,提前!
【问题讨论】:
标签: ruby-on-rails database model-view-controller model has-many-through