2017-10-06 75 views
1

嗨join_table我有一个主要的模式,与食材的has_many关联,这也的has_many食谱,我的连接表食谱是recipes_ingredients,连接表有列recipe_id,ingredient_id和数量。数量只是该配方中该配料使用次数的字符串。添加属性,从初级形式

enter image description here

我已经创建的配方,并在创建并同时数据库保存它的形式保存了在形式给出一个嵌套属性的任何成分......我不能为我的生活想出了如何使用这个相同的表格为这个连接表添加数量。我将不胜感激您提供的任何帮助......非常感谢您提前。

# models/recipe.rb 
    class Recipe < ApplicationRecord 
     belongs_to :user 
     has_many :recipe_ingredients 
     has_many :ingredients, through: :recipe_ingredients 
     validates :name, :content, :cook_time, presence: true 

     def ingredients_attributes=(ingredients_hash) 
     ingredients_hash.each do |i, ingredients_attributes| 
      if ingredients_attributes[:name].present? 
      ingredient = Ingredient.find_or_create_by(name: ingredients_attributes[:name].capitalize!) 
      if !self.ingredients.include?(ingredient) 
       self.recipe_ingredients.build(:ingredient => ingredient) 
      end 
      end 
     end 
    end 

# models/ingredient.rb 
class Ingredient < ApplicationRecord 
    has_many :recipe_ingredients 
    has_many :recipe, through: :recipe_ingredients 
    validates :name, presence: true 
end 

# models/recipe_ingredient.rb 
class RecipeIngredient < ApplicationRecord 
    belongs_to :ingredient 
    belongs_to :recipe 
end 

    # form 
    <%= form_with(model: instruction, local: true) do |form| %> 
    <% if instruction.errors.any? %> 
    <div id="error_explanation"> 
    <h4><%= pluralize(instruction.errors.count, "error") %> prohibited 
    this instruction from being saved:</h4> 

    <ul> 
    <% instruction.errors.full_messages.each do |message| %> 
    <li><%= message %></li> 
    <% end %> 
    </ul> 
    </div> 
    <% end %> 

<div class="container"> 
<div class="row"> 
<div class="col-sm-6"> 
    <h3 class="text-center">Recipe</h3> 
    <div class="fields"> 
    <%= form.label :name %><br> 
    <%= form.text_field :name, :placeholder => "Name" %><br> 
    <%= form.label "Instructions" %><br> 
    <%= form.text_area :content, :placeholder => "Recipe 
    Instructions" %><br> 
    <%= form.label :cook_time %><br> 
    <%= form.text_field :cook_time, :placeholder => "(ex,. 45 
    mins)" %><br> 
    <%= form.hidden_field :user_id, value: params[:user_id] %> 
    </div> 
    </div> 

    <div class="col-sm-6"> 
    <h3 class="text-center">Ingredients</h3> 
    <div class="row"> 
     <div class="col-sm-6 checkbox"> 
      <%= form.collection_check_boxes(:ingredient_ids, 
     Ingredient.all, :id, :name) %> 
     </div> 
     <div class="col-sm-6"> 
      <%= form.fields_for :ingredients do 
     |ingredient_builder| %> 
       <%= ingredient_builder.text_field :name %><br> 
      <% end %> 
      </div> 
     </div> 
    </div> 
    </div> 

    <div class="row justify-content-center submit-row"> 
    <div class="fields text-center"> 
     <%= form.submit %> 
    </div> 
    </div> 


</div>[![enter image description here][1]][1] 
+0

你有没有看到https://stackoverflow.com/a/21060278/3109182? – Anthony

回答