1
嗨join_table我有一個主要的模式,與食材的has_many關聯,這也的has_many食譜,我的連接表食譜是recipes_ingredients,連接表有列recipe_id,ingredient_id和數量。數量只是該配方中該配料使用次數的字符串。添加屬性,從初級形式
我已經創建的配方,並在創建並同時數據庫保存它的形式保存了在形式給出一個嵌套屬性的任何成分......我不能爲我的生活想出瞭如何使用這個相同的表格爲這個連接表添加數量。我將不勝感激您提供的任何幫助......非常感謝您提前。
# 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]
你有沒有看到https://stackoverflow.com/a/21060278/3109182? – Anthony