我创建了两个表库存和inventory_transaction。库存has_many:inventory_transaction和inventory_transaction belongs_to:inventory。这是表格字段
create_table "inventorys", force: :cascade do |t|
t.string "name"
t.integer "current_stock"
end
create_table "inventory_transactions", force: :cascade do |t|
t.string "t_type"
t.integer "t_quantity"
t.integer "inventory_id"
end
我想做的是每当保存新的inventory_transaction时自动更新库存current_stock。等式是这样的
if t_type = 'in'
inventory.current_stock = inventory.current_stock + t_quantity
else
inventory.current_stock = inventory.current_stock - t_quantity
end
关于如何在我的ruby on rails项目中实现等式的任何想法?
答案 0 :(得分:0)
将此添加到您的InventoryTransaction
:
after_save :update_current_stock
def update_current_stock
if t_type == 'in'
inventory.update current_stock: inventory.current_stock + t_quantity
else
inventory.update current_stock: inventory.current_stock - t_quantity
end
end
end