首页 > 解决方案 > Rails has_many,:通过表格将变量添加到连接表

问题描述

我正在尝试构建一个用于存储食谱的应用程序,以便我可以(最终)根据食谱成分构建购物清单。

我正在苦苦挣扎的是能够将成分与基于它们的食谱联系起来measures,即一个食谱可以使用300 克面粉和一撮盐,而另一个食谱可能使用两杯面粉和一茶匙盐。

我已经用三个表设置了数据库RecipesMeasuresIngredients。但是,我在尝试创建基本表单元素时遇到了困难,这样我就可以将unit(例如克、杯或毫升)和数量(1 或 500)与度量的成分相关联。那么,我如何将表格放在一起以允许这样做?

我通过为所有可用成分添加一组复选框来开始表单,但这仅允许链接或不链接成分 - 我不知道还添加有关要在此处添加的连接表的元素的信息.

这是recipes_controller:

def new
  @recipe = Recipe.new

  @ingredients = Ingredient.all
end

def edit
  @recipe = Recipe.find(params[:id])
  @ingredients = Ingredient.all
end

def create
  @recipe = Recipe.new(recipe_params)

  if @recipe.save
    redirect_to @recipe
  else
    render 'new'
  end
end
...
private
  def recipe_params
    params.require(:recipe).permit(:name, :method, :category, ingredient_ids:[])
  end

和模型:

class Recipe < ApplicationRecord
  has_many :measures
  has_many :ingredients, through: :measures
  accepts_nested_attributes_for :ingredients
end

class Measure < ApplicationRecord
  belongs_to :ingredient
  belongs_to :recipe
  accepts_nested_attributes_for :ingredient
end

class Ingredient < ApplicationRecord
  has_many :measures
  has_many :recipes, through: :measures
end

基本配方形式部分:

# /views/recipes/_form.html.erb
<%= form_for(@recipe) do |form| %>     
  <p>
    <%= form.label :name %><br>
    <%= form.text_field :name %>
  </p>

  <p>
    <%= form.collection_check_boxes :ingredient_ids, @ingredients, :id, :name %>
  </p>

  <p>
    <%= form.fields_for :measures do |ff| %>
      <% @ingredients.each do |ingredient| %>
        <%= ff.label :unit %>
        <%= ff.text_field :unit %> | 
        <%= ff.label :quantity %>
        <%= ff.text_field :quantity %> | 
        <%= ff.label ingredient.name %>
        <%= ff.check_box :ingredient_id %>     
        <br>
      <% end %>
    <% end %>
  </p>

  <p>
    <%= form.submit %>
  </p>

<% end %>

谢谢你的帮助!

标签: ruby-on-railsformsjoinnested-formshas-many-through

解决方案


推荐阅读