ruby-on-railsruby-on-rails-4nested-formsnested-form-for

"Invalid association": nested_form_for with has_many through


I am trying to dynamically add an arbitrary number of ingredients to a shoppping list using the nested_form gem. This is a has_many through relationship, and I'm having trouble finding exactly what I need. I'm getting the following error when trying to render the new action:

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

Here are my models:

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

My 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

I know that my new action is not correct, but to be honest I am very lost with how a has_many_through relationship is supposed to work with nested fields.

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

I'm using Rails 4.2.5, ruby 2.2.1, and nested_form 0.3.2. nested_form is listed in my application.js as //= require jquery_nested_form.


Solution

  • accepts_nested_attributes_for :shopping_list_ingredients

    f.fields_for :ingredients

    Your params will come through as ingredients_attributes and your model won't know what to do with them as it will be looking for shopping_list_ingredients_attributes.

    You need to have both of these matching for it to work.