我正在嘗試構建一個基本的食譜應用程序,但遇到了麻煩,允許用戶爲一個配方輸入多個配料。成分的允許參數數組最終爲空。所以我想我的問題是 - 我該如何准許一系列配料?如何使用Rails爲同一模型獲取多個記錄form_for
我的控制器:
class RecipesController < ApplicationController
def new
@recipe = Recipe.new
@ingredient = Ingredient.new
end
def create
safe_params = params.require(:recipe).permit(:title, :instruction, :category_id)
ingredient_params = params.require(:recipe).permit(:ingredient => [])
@recipe = Recipe.new(safe_params)
@recipe.save
ingredient_params.each do |i|
@recipe.ingredients << Ingredient.find_or_create_by(name: i[:ingredient][:name])
end
render body: YAML::dump(ingredient_params)
#redirect_to index_path(id: @recipe.id)
end
end
形式:
<%= form_for(@recipe, :url => create_path) do |f| %>
<%= f.label :category %>
<%= f.select :category_id, options_for_select(Category.all.map{|c|[c.title, c.id]}) %>
<%= f.label :title %>
<%= f.text_field :title%>
<%= f.label :instruction %>
<%= f.text_area(:instruction, size: "50x10") %>
<%= f.fields_for "ingredients[]", @ingredient do |i| %>
<%= i.label :name %>
<%= i.text_field :name %>
<%= i.text_field :name %>
<%= i.text_field :name %>
<% end %>
<%= f.submit "Submit" %>
<% end %>
型號:
class Recipe < ActiveRecord::Base
has_and_belongs_to_many :ingredients
accepts_nested_attributes_for :ingredients
belongs_to :category
end
class Category < ActiveRecord::Base
has_many :recipes
end
class Ingredient < ActiveRecord::Base
has_and_belongs_to_many :recipes
end
什麼允許錯誤你能看到日誌? – chaitanya