Nested Attributes Error: no implicit conversion of String into Integer

Nested Attributes Error: no implicit conversion of String into Integer

我的Item模型属于我的Order模型,我的Order模型有很多Items。当我尝试传递以下参数时:

{"utf8"=>"✓", "authenticity_token"=>"mPKksp+W5lZc7+lrc90trtCzX+UtPj4PI8boNf7vb+nneMF/J5SSBz8Nmh+CQ//DkmuVP2MJf7gS3oLqpZcM2Q==", "order"=>{"special_instructions"=>"", "item_attributes"=>{"topping_ids"=>["1", "2", "5"]}}, "commit"=>"Save"}

我收到以下错误:

no implicit conversion of String into Integer

我在订单控制器中创建操作时发生错误:

@order = Order.new(order_params)

这是我的参数方法的样子:

def order_params
  params.require(:order).permit(:completed, :special_instructions, items_attributes: [ :size, topping_ids: [] ])
end

这是我的订单模型:

class Order < ActiveRecord::Base
  belongs_to :user
  has_many :items
  accepts_nested_attributes_for :items
end

这是我的物品模型:

class Item < ActiveRecord::Base
  belongs_to :order
  has_many :sizes
  has_many :item_toppings
  has_many :toppings, through: :item_toppings
  has_many :inverse_item_toppings, class_name: 'ItemTopping', foreign_key: 'item_id'
  has_many :inverse_toppings, through: :inverse_item_toppings, source: :item
  accepts_nested_attributes_for :sizes, reject_if: :all_blank, allow_destroy: true
end

这是我的架构的相关部分

create_table "item_toppings", force: :cascade do |t|
  t.integer  "item_id"
  t.integer  "topping_id"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

create_table "items", force: :cascade do |t|
  t.string   "name"
  t.datetime "created_at",                  null: false
  t.datetime "updated_at",                  null: false
  t.string   "description"
  t.boolean  "seasonal",    default: false
  t.boolean  "active",      default: false
  t.string   "kind"
  t.integer  "toppings_id"
  t.string   "qualifier"
  t.integer  "order_id"
end

create_table "orders", force: :cascade do |t|
  t.datetime "created_at",                           null: false
  t.datetime "updated_at",                           null: false
  t.boolean  "completed",            default: false
  t.integer  "user_id"
  t.string   "special_instructions"
end

我很确定这与我的某些参数需要是数组而不是散列有关,但我无法根据我工作过的类似帖子找出我的具体问题通过.

猜测:

@order = Order.new(order_params)

至:

order_params_hash = order_params 

order_params_hash[:order][:item_attributes][:topping_ids].map! do |topping_id| 
  topping_id.to_i 
end

@order = Order.new(order_params_hash)

我认为这是因为您将一个字符串数组传递给 topping_ids,并且相应的数据库列设置为存储整数。

您可以调用 to_i 显式地将字符串数组转换为整数,或者传递一个整数数组。

据我所知,因为我有 has_many 关系,所以我的 items_attributes 值需要是一个哈希数组:

{"items_attributes"=>[{"topping_ids"=>['1', '2', '5', '30']}]}

而不是

{"items_attributes"=>{"topping_ids"=>['1', '2', '5', '30']}}

我认为消息错误与 Ruby 需要数组索引而不是散列键有关。