从主表单向join_table添加属性

时间:2017-10-06 12:24:40

标签: sql ruby-on-rails ruby activerecord

您好我有一个主要模型,配方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]