Expected Product, Array Issue

I have a rails 4 application that has a params block that looks like this:

def store_params params.require(:store).permit(:name, :description, :user_id, products_attributes: [:id, :type, { productFields: [:type, :content ] } ]) end 

but I get an error:

 ActiveRecord::AssociationTypeMismatch in StoresController#create ProductField expected, got Array 

The options I'm trying to insert are as follows:

 Parameters: {"utf8"=>"✓", "store"=>{"name"=>"fdsaf", "description"=>"sdfd","products_attributes"=>{"0"=>{"productFields"=>{"type"=>"", "content"=>""}}}}, "type"=>"Magazine", "commit"=>"Create store"} 

My models

  • Save (has has_many :products )
  • Product (has has_many :productFields and belongs_to :store )
  • ProductField (has belongs_to :product )

My view looks like this:

 <%= f.fields_for :products do |builder| %> <%= render 'product_fields', f: builder %> <% end %> 

and then the product_fields particle:

 <%= f.fields_for :productFields do |builder| %> <%= builder.text_field :type%> <%= builder.text_area :content %> <% end %> 
+7
ruby ruby-on-rails params
source share
2 answers

Make sure your product and store models have:

 accepts_nested_attributes_for 

inside them.

Then, if your nested field calls for this, make sure you create them (in the controller), something like:

 product = @store.products.build product.productFields.build 
+7
source share

First, you must set accepts_nested_attributes_for in your models, such as

 class Store < ActiveRecord::Base has_many :products accepts_nested_attributes_for :products end class Product < ActiveRecord::Base has_many :product_fields belongs_to :store accepts_nested_attributes_for :product_fields end class ProductField < ActiveRecord::Base belongs_to :products end 

Secondly, your store_params should look like this

 def store_params params.require(:store).permit(:name, :description, :user_id, products_attributes: [:id, :type, { product_fields_attributes: [:type, :content ] } ]) end 
+3
source share

All Articles