预期的ProductField,有阵列问题

时间:2014-05-09 18:02:12

标签: ruby-on-rails ruby params

我有一个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"}

我的模特

  1. 商店(有一个has_many :products
  2. 产品(包含has_many :productFieldsbelongs_to :store
  3. ProductField(有一个belongs_to :product
  4. 我的观点如下:

    <%= 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 %>
    

2 个答案:

答案 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