"Invalid association": nested_form_for 通过 has_many

"Invalid association": nested_form_for with has_many through

我正在尝试使用 nested_form gem 将任意数量的成分动态添加到购物清单中。这是一个 has_many through 关系,我无法准确找到我需要的东西。尝试呈现 new 操作时出现以下错误:

Invalid association. Make sure that accepts_nested_attributes_for is used for :ingredients association.

这是我的模型:

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

我的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

我知道我的新操作不正确,但老实说,我对 has_many_through 关系应该如何与嵌套字段一起工作感到非常迷惑。

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 %>

我正在使用 Rails 4.2.5、ruby 2.2.1 和 nested_form 0.3.2。 nested_form 在我的 application.js 中列为 //= require jquery_nested_form

accepts_nested_attributes_for :shopping_list_ingredients

f.fields_for :ingredients

您的参数将作为 ingredients_attributes 出现,您的模型将不知道如何处理它们,因为它将寻找 shopping_list_ingredients_attributes.

您需要同时满足这两个条件才能正常工作。