hazimIskandar hazimIskandar - 4 months ago 8
Ruby Question

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?

Answer

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
Comments