My Item model belongs to my Order model, and my Order model has many Items. When I attempt to pass in the following params:
{"utf8"=>"✓", "authenticity_token"=>"mPKksp+W5lZc7+lrc90trtCzX+UtPj4PI8boNf7vb+nneMF/J5SSBz8Nmh+CQ//DkmuVP2MJf7gS3oLqpZcM2Q==", "order"=>{"special_instructions"=>"", "item_attributes"=>{"topping_ids"=>["1", "2", "5"]}}, "commit"=>"Save"}
I receive the following error:
no implicit conversion of String into Integer
The error occurs in my create action in my Orders controller:
@order = Order.new(order_params)
This is what my params method looks like:
def order_params
params.require(:order).permit(:completed, :special_instructions, items_attributes: [ :size, topping_ids: [] ])
end
Here is my Order model:
class Order < ActiveRecord::Base
belongs_to :user
has_many :items
accepts_nested_attributes_for :items
end
Here is my Item model:
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
And here are the relevant parts of my schema
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
I'm pretty sure this has something to do with some part of my params needing to be an array instead of a hash, but I can't figure out my specific problem based off of similar posts I've worked through.
From what I can tell, because I have a has_many relationship, my items_attributes value needed to be an array of hashes:
{"items_attributes"=>[{"topping_ids"=>['1', '2', '5', '30']}]}
Instead of
{"items_attributes"=>{"topping_ids"=>['1', '2', '5', '30']}}
I believe the message error is related to Ruby expecting an array index – not a hash key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With