ruby on rails - "Invalid association": nested_form_for with has_many through -


i trying dynamically add arbitrary number of ingredients shoppping list using nested_form gem. has_many through relationship, , i'm having trouble finding need. i'm getting following error when trying render new action:

invalid association. make sure accepts_nested_attributes_for used :ingredients association. 

here 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 new action not correct, honest lost how has_many_through relationship supposed work nested fields.

shopping_list/new.html.erb

<h1>create new shopping list</h1> <%= nested_form_for @shopping_list |f| %>   <p>    <%= f.fields_for :ingredients |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, , nested_form 0.3.2. nested_form listed in application.js //= require jquery_nested_form.

accepts_nested_attributes_for :shopping_list_ingredients

f.fields_for :ingredients

your params come through ingredients_attributes , model won't know them looking shopping_list_ingredients_attributes.

you need have both of these matching work.


Comments

Popular posts from this blog

gridview - Yii2 DataPorivider $totalSum for a column -

java - Suppress Jboss version details from HTTP error response -

Sass watch command compiles .scss files before full sftp upload -