2017-04-08 82 views
0

我得到的錯誤「符號的隱式轉換成整數」符號的隱式轉換爲整數錯誤與哈希

這裏是我的代碼:

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

的錯誤是在該行:

num = self_product[:stock] 

回答

2

self_product被視爲一個數組(或類似數組的東西),因此它期望的是一個數字索引,而不是像對散列或活動記錄實例所期望的那樣符號。

問題就在這裏:

self_product = Product.where(id: product.id) 

這會返回一個ActiveRecord關係的對象。使用[]運算符將運行查詢並返回第n個項目。

你可能想是這樣的:

num = Product.find(product.id).stock 

但是,如果您有購物車項目協會product設置權,你不應該需要做的。你應該可以這樣做:

num = product.stock 
+1

真棒老人感謝了很多,與num = product.stock合作呵呵!我在哪裏給你啤酒的?哈哈謝謝!!! –

+0

對我有一個慶祝啤酒:D – mahemoff

相關問題