Expected ProductField, got array issue

随声附和 提交于 2019-12-22 04:15:10

问题


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

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

but I'm getting the error:

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

The parameters I'm trying to insert look like:

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

My models are

  1. Store (has a has_many :products)
  2. Product (has a has_many :productFields and belongs_to :store)
  3. ProductField (has a belongs_to :product)

My view looks like:

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

and then the product_fields partial:

<%= f.fields_for :productFields do |builder| %>
  <%= builder.text_field :type%>
  <%= builder.text_area :content %>
<% end %>

回答1:


Make sure your Product and Store models have:

accepts_nested_attributes_for

inside them.

Then, if your calling nested fields_for like that, make sure you build them (in the controller), something like:

product = @store.products.build
product.productFields.build



回答2:


Firstly you should have set accepts_nested_attributes_for in your models like this

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


来源:https://stackoverflow.com/questions/23571220/expected-productfield-got-array-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!