我有一个rails 4应用程序,它有一个params块,看起来像:
def store_params
params.require(:store).permit(:name, :description, :user_id, products_attributes: [:id, :type, { productFields: [:type, :content ] } ])
end
但我收到了错误:
ActiveRecord::AssociationTypeMismatch in StoresController#create
ProductField expected, got Array
我试图插入的参数如下:
Parameters: {"utf8"=>"✓", "store"=>{"name"=>"fdsaf", "description"=>"sdfd","products_attributes"=>{"0"=>{"productFields"=>{"type"=>"", "content"=>""}}}}, "type"=>"Magazine", "commit"=>"Create store"}
我的模特
has_many :products
)has_many :productFields
和belongs_to :store
)belongs_to :product
)我的观点如下:
<%= f.fields_for :products do |builder| %>
<%= render 'product_fields', f: builder %>
<% end %>
然后product_fields partial:
<%= f.fields_for :productFields do |builder| %>
<%= builder.text_field :type%>
<%= builder.text_area :content %>
<% end %>
答案 0 :(得分:7)
确保您的产品和商店模型具有:
accepts_nested_attributes_for
在他们里面。
然后,如果您调用嵌套的fields_for,请确保构建它们(在控制器中),如:
product = @store.products.build
product.productFields.build
答案 1 :(得分:3)
首先,您应该在模型中设置accepts_nested_attributes_for
,如下所示
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
其次,您的store_params
应该是这样的
def store_params
params.require(:store).permit(:name, :description, :user_id, products_attributes: [:id, :type, { product_fields_attributes: [:type, :content ] } ])
end