嵌套属性错误:没有将字符串隐式转换为整数

tro*_*orn 0 ruby-on-rails params

我的项目模型属于我的订单模型,我的订单模型有很多项目。当我尝试传递以下参数时:

{"utf8"=>"?", "authenticity_token"=>"mPKksp+W5lZc7+lrc90trtCzX+UtPj4PI8boNf7vb+nneMF/J5SSBz8Nmh+CQ//DkmuVP2MJf7gS3oLqpZcM2Q==", "order"=>{"special_instructions"=>"", "item_attributes"=>{"topping_ids"=>["1", "2", "5"]}}, "commit"=>"Save"}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

no implicit conversion of String into Integer
Run Code Online (Sandbox Code Playgroud)

该错误发生在我的Orders控制器中的create操作中:

@order = Order.new(order_params)
Run Code Online (Sandbox Code Playgroud)

这是我的params方法的样子:

def order_params
  params.require(:order).permit(:completed, :special_instructions, items_attributes: [ :size, topping_ids: [] ])
end
Run Code Online (Sandbox Code Playgroud)

这是我的订单模型:

class Order < ActiveRecord::Base
  belongs_to :user
  has_many :items
  accepts_nested_attributes_for :items
end
Run Code Online (Sandbox Code Playgroud)

这是我的物品模型:

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
Run Code Online (Sandbox Code Playgroud)

这是我架构的相关部分

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
Run Code Online (Sandbox Code Playgroud)

我很确定这与我的参数的某些部分有关,这些部分需要是数组而不是哈希,但是我无法根据自己研究过的类似文章来弄清楚我的特定问题。

tro*_*orn 5

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

{"items_attributes"=>[{"topping_ids"=>['1', '2', '5', '30']}]}
Run Code Online (Sandbox Code Playgroud)

代替

{"items_attributes"=>{"topping_ids"=>['1', '2', '5', '30']}}
Run Code Online (Sandbox Code Playgroud)

我认为消息错误与Ruby期望数组索引有关,而不是与哈希键有关。

  • 空数组使得 items_attributes 值是一个数组,因此 items_attributes[] 将使参数“item_attributes”=&gt;[{}],而如果没有数组,它将只是“item_attributes”=&gt;{} (2认同)