J'essaie d'ajouter dynamiquement un nombre arbitraire d'ingrédients à une liste shoppping en utilisant la gemme nested_form
. C'est une relation has_many through
, et j'ai du mal à trouver exactement ce dont j'ai besoin. Je reçois l'erreur suivante en essayant de rendre l'action new
:"Invalid association": nested_form_for avec has_many à
Invalid association. Make sure that accepts_nested_attributes_for is used for :ingredients association.
Voici mes modèles:
class ShoppingList < ActiveRecord::Base
has_many :shopping_list_ingredients
has_many :ingredients, :through => :shopping_list_ingredients
accepts_nested_attributes_for :shopping_list_ingredients, allow_destroy: :true
end
class Ingredient < ActiveRecord::Base
has_many :shopping_list_ingredients
has_many :shoping_lists, :through => :shopping_list_ingredients
end
class ShoppingListIngredient < ActiveRecord::Base
belongs_to :shopping_list
belongs_to :ingredient
end
Mon shopping_list_controller.rb:
class ShoppingListsController < ApplicationController
def index
@shopping_lists = ShoppingList.all
end
def show
@shopping_list = ShoppingList.find(params[:id])
end
def new
@shopping_list = ShoppingList.new
@shopping_list_ingredients = @shopping_list.shopping_list_ingredients.build
@ingredients = @shopping_list_ingredients.build_ingredient
end
def create
@shopping_list = ShoppingList.new(shopping_list_params)
end
private
def shopping_list_params
params.require(:shopping_list).permit(:id, shopping_list_ingredients_attributes: [:id, ingredient: [:id, :name, :amount]])
end
end
Je sais que mon Une nouvelle action n'est pas correcte, mais pour être honnête, je suis très perdu sur la façon dont une relation has_many_through est supposée fonctionner avec des champs imbriqués.
shopping_list/new.html.erb
<h1>Create a new shopping list</h1>
<%= nested_form_for @shopping_list do |f| %>
<p>
<%= f.fields_for :ingredients do |ff| %>
<%= ff.label :name %>
<%= ff.text_field :name %>
<%= ff.link_to_remove "Remove Item" %>
<% end %>
<%= f.link_to_add "Add Item", :ingredients %>
<p>
<% f.submit %>
</p>
<% end %>
<%= link_to "Back", shopping_lists_path %>
J'utilise Rails 4.2.5, rubis 2.2.1 et 0.3.2 nested_form. nested_form est répertorié dans my application.js en tant que //= require jquery_nested_form
.
Merci, j'ai ajouté 'accept_nested_attributes_for: ingredients' à mon modèle shopping_list et cela a fonctionné parfaitement. –