预期的ProductField,得到arrays问题
我有一个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
) - ProductField(有一个
belongs_to :product
)
我的观点如下:
然后product_fields部分:
确保您的产品和商店模型具有:
accepts_nested_attributes_for
在他们里面。
然后,如果您调用嵌套的fields_for,请确保构建它们(在控制器中),例如:
product = @store.products.build product.productFields.build
首先,你应该像这样在你的模型中设置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