如何从 Rails 中具有匹配 ID 的联接 table 中获取记录数 5

How to get count of records from join table with matching ID in Rails 5

我有 2 个模型。膳食和食物。一顿饭可以有很多食物,一个食物可以是多顿饭的一部分。他们有一个多对多的关联,由 has_many :through 完成。连接模型称为 MealFood,连接 table 称为 meal_foods。 创建膳食时,您可以根据需要添加任意数量的食物。有一个 jQuery 按钮,当您单击它时,它会自动在表单中附加一个新输入,然后您可以在那里输入食品。 我怎样才能使膳食的编辑视图显示尽可能多的带有食品名称的输入字段。

膳食控制器:

def create
    @meal = current_user.meals.new(meal_params)

    if @meal.save
        @meal.update(total_calories: @meal.calc_total_calories, total_carbohydrates:    @meal.calc_total_carbohydrates, total_proteins: @meal.calc_total_proteins, total_fat: @meal.calc_total_fat)

        redirect_to @meal
    else
        render 'new'
    end
end

def edit
    @meal = Meal.find(params[:id])
end


def update
    if @meal.update(meal_params)
        @meal.update(total_calories: @meal.calc_total_calories, 
        total_carbohydrates: @meal.calc_total_carbohydrates,
        total_proteins: @meal.calc_total_proteins,
        total_fat: @meal.calc_total_fat)

        redirect_to @meal
    else
        render 'edit'
    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">
        <label class="input-dropdown">Food Item #1</label>
        <%= select_tag "meal[food_ids][]", options_from_collection_for_select(Food.all, "id", "name") %>
    </div>

    <div class="field submit">
        <%= f.submit class: "button button-highlight button-block" %>
    </div>
<% end %>

提前致谢!

因为这使用连接 table,我假设您不希望用户实际上能够编辑 Food 记录本身 - 他们应该编辑 MealFood 记录,对吧?

在这种情况下,您应该能够查询 meal.meal_foods 以获取要编辑的连接 table 记录。您的查询可能如下所示:

@meal_foods = @meal.meal_foods.includes(:food)

.includes(:food)会auto-load所有你需要的食物记录,避免你出现N+1查询问题

那么在你看来,你可以这样做:

<div class="field">
  <% @meal_foods.each do |mf| %>
    <... your input element for each record />
  <% end %>
</div>

如果您确实希望您的用户能够自己修改 Food 记录,那么您可以使用相同的策略,但只需使用您已经创建的 through 关联。