Reputation: 13771
I have a Task Order that has_many Invoices. Task Order has an attribute called "invoicedAmount". Invoice has an attribute called "amount". I am trying to make a callback where whenever I add or delete an invoice, the "invoicedAmount" field updates accordingly. Right now I am able to make it calculate on the fly, but now I want to save it to the database. Here is my Invoice model:
class Invoice < ActiveRecord::Base
belongs_to :task_order
validates_presence_of :task_order_id
after_save :update_task_order_invoiced_amount, notice: ':)!'
after_destroy :update_task_order_invoiced_amount
def update_task_order_invoiced_amount
@task_orders = TaskOrder.all
@invoices = Invoice.all
@task_orders.each do |task_order|
task_order.invoicedAmount = task_order.invoices.sum(:amount)
end
end
end
Any guidance would be greatly appreciated!
Upvotes: 0
Views: 33
Reputation: 3352
You probably don't want to recalculate all TaskOrder
records, but only changed one. So your update_task_order_invoiced_amount
should look something like this:
def update_task_order_invoiced_amount
task_order.invoicedAmount = task_order.invoices.sum(:amount)
task_order.save
end
Upvotes: 1