I get the error "no implicit conversion of Symbol into Integer"
Here is my code:
# == Schema Information
#
# Table name: my_payments
#
# id :integer not null, primary key
# email :string
# ip :string
# status :string
# fee :decimal(6, 2)
# paypal_id :string
# total :decimal(8, 2)
# created_at :datetime not null
# updated_at :datetime not null
# shopping_cart_id :integer
#
class MyPayment < ActiveRecord::Base
belongs_to :shopping_cart
include AASM
aasm column: "status" do
state :created, initial: true
state :payed
state :failed
event :pay do
after do
shopping_cart.pay!
self.update_stock_products()
end
transitions from: :created, to: :payed
end
end
def update_stock_products
self.shopping_cart.in_shopping_carts.map { |i_sh|
product = i_sh.product
self_product = Product.where(id: product.id)
num = self_product[:stock]
res = num - i_sh.num_products
Product.update(product.id,stock: res)
}
end
end
The error is in the line:
num = self_product[:stock]
self_product is being treated as an array (or array-like thing), hence it's expecting a numeric index, not a symbol as you'd expect for a hash or active record instance.
The issue is here:
self_product = Product.where(id: product.id)
This returns an ActiveRecord Relation object. Using [] operator on it will run the query and give back the nth item.
You probably want something like:
num = Product.find(product.id).stock
However, if you have the shopping cart item association to product
setup right, you shouldn't need to do that. You should be able to just do:
num = product.stock