Rails: Update parent attribute when (has_many) child record(s) is/are updated

Viewed 259

I have the following structure

class Order < ActiveRecord::Base
  has_many :order_lines, inverse_of: :order, validate: false, autosave: true
end

class OrderLine < ActiveRecord::Base
  belongs_to :order, inverse_of: :order_lines, touch: true, counter_cache: :line_count
end

I would like a parent(Order) attribute to be updated when the children(OrderLine) records are updated. Let's say Order Total is to be updated when the OrderLine Price/Quantity is updated.

I could add an after_save/commit callback on the OrderLine level OR add after_commit callback(because of touch: true) on the Order level to calculate and update the total.

However, when the number of lines is huge(more than 100), it executes callback on each line update, which is having performance impacts. Also, there are feature flows where individual/multiple lines get updated without updating the parent(Order) record. So I do need to have the callback on line level as well to update the total in such scenarios.

Is there a way to update the parent attribute(total) here in a more performant way?

0 Answers
Related