"Недопустимая ассоциация": nested_form_for с has_many через

Я пытаюсь динамически добавить произвольное количество ингредиентов в список покупок, используя nested_form драгоценный камень. Это 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,

1 ответ

Решение

accepts_nested_attributes_for :shopping_list_ingredients

f.fields_for :ingredients

Ваши параметры появятся как ingredients_attributes и ваша модель не будет знать, что с ними делать, так как будет искать shopping_list_ingredients_attributes,

Вы должны иметь оба этих соответствия для его работы.

Другие вопросы по тегам