“无效关联”:带有has_many的nested_form_for

时间:2016-03-01 03:37:11

标签: ruby-on-rails ruby-on-rails-4 nested-forms nested-form-for

我正在尝试使用nested_form gem动态地将任意数量的成分添加到shoppping列表中。这是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

我知道我的新动作不正确,但说实话,我很遗憾a_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

1 个答案:

答案 0 :(得分:1)

  

accepts_nested_attributes_for :shopping_list_ingredients

     

f.fields_for :ingredients

你的参数将以ingredients_attributes的形式出现,你的模型不知道如何处理它们,因为它会寻找shopping_list_ingredients_attributes

您需要同时使用这两种方法才能正常工作。