2016-07-17 13 views
1

私は2つのテーブルインベントリとinventory_transactionを作成しました。在庫has_many:inventory_transactionとinventory_transaction belongs_to:在庫。ここにテーブルのフィールドがありますruby​​ on railsの別のテーブルフィールドからテーブルフィールドを更新する方法

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 

私のルビープロジェクトの方程式をどのように実装するかについてのアイデアはありますか?

答えて

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 
+0

それが動作します。私はちょうどt_typeを追加する必要があります=== 'in' – hazimIskandar

+0

あなたは '=='を意味すると思います。私は答えを更新しました。 –

関連する問題