当用户购买产品时,我需要调整产品的库存(product.stock
)。如果用户想要的数量大于可用数量,那么我想在product.backorder
存储我需要订购的数量。
以下模型中的代码是我提出的算法对我有意义,但是当我添加:backorder = :backorder + amount.abs
和:stock = 0
时,我在控制器中收到以下错误。这些变量是产品表的一部分,也许我不能从购买模型中写入它们?
syntax error, unexpected '=', expecting keyword_end
def show
@order = Order.find(params[:id])
@purchases = @order.purchases #this line is highlighted
end
class Purchase < ActiveRecord::Base
#... other code
belongs_to :product
after_create :adjust_inventory
def adjust_inventory
amount = :stock - quantity
unless amount < 0
product.decrement!(:stock, quantity)
else
backordered = amount.abs
:backorder = :backorder + amount.abs
:stock = 0
product.save
purchase.save
end
end
end
...
t.string "name"
t.decimal "price"
t.integer "stock"
t.integer "backorder"
...
t.string "name"
t.integer "quantity" # amount client would like to purchase
t.decimal "price"
t.integer "backordered" # amount to restock and give to the client
答案 0 :(得分:2)
我还没有对此进行过测试,但我确信它会更新产品并购买 记录你的预期方式。
class Purchase < ActiveRecord::Base
belongs_to :product
after_create :adjust_inventory
def adjust_inventory
amount = product.stock - quantity
unless amount < 0
product.decrement!(:stock, quantity)
else
product.update(
backorder: (product.backorder || 0) + amount.abs,
stock: 0
)
self.backordered = amount.abs
save
end
end
end