简体   繁体   中英

How to update table fields from another table fields in ruby on rails

I have created two table inventory and inventory_transaction. inventory has_many: inventory_transaction and inventory_transaction belongs_to:inventory. here are the table fields

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

What i want to make is automatically update inventory current_stock whenever a new inventory_transaction is save. the equation is like this

if t_type = 'in'
   inventory.current_stock = inventory.current_stock + t_quantity
else
   inventory.current_stock = inventory.current_stock - t_quantity
end

Any idea on how to implement the equation in my ruby on rails project?

Add this to your 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM