0

我試圖用nested_form gem動態地將任意數量的配料添加到購物清單中。這是一個has_many through的關係,我很難找到我需要的東西。我越來越想渲染new動作時出現以下錯誤:「無效的關聯」:nested_form_for with has_many到

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,2.2.1紅寶石和nested_form 0.3.2。 nested_form在我的application.js中列爲//= require jquery_nested_form

回答

1

accepts_nested_attributes_for :shopping_list_ingredients

f.fields_for :ingredients

你PARAMS會通過爲ingredients_attributes和你的模型將不知道如何處理他們,因爲它會找shopping_list_ingredients_attributes

你需要有這兩個匹配才能工作。

+0

謝謝,我在我的shopping_list模型中增加了'accep_nested_attributes_for:ingredients',這個工作很完美。 –