toy
toy

Reputation: 553

observe activerecord relations

I like to observe adding an object to my has_many relation without saving them to the database.
So when I add a LineItem to my Order I like to call Order::calculate_total to update the actual total value.

o = Order.new
o.line_items << LineItem.new # should call calculate_total from order-object

but there are no observers for the build-method of my LineItem.

Upvotes: 1

Views: 794

Answers (2)

Fran&#231;ois Beausoleil
Fran&#231;ois Beausoleil

Reputation: 16515

I retract myself. I just found out about association callbacks: ActiveRecord::Associtions::ClassMethods, search for "Association callbacks". Essentially:

class Order < ActiveRecord::Base
  has_many :line_items, :after_add => :calculate_order_total
end

You also have access to before_add, before_remove and after_remove.

Upvotes: 4

Fran&#231;ois Beausoleil
Fran&#231;ois Beausoleil

Reputation: 16515

Do it differently:

class Order < ActiveRecord::Base
  def add_line_item(line_item)
    self.line_items << line_item
    self.calculate_total
  end
end

But I question why you need to calculate the total on each add of the line item. The same can be achieved if you calculate only once after adding all line items.

Upvotes: 0

Related Questions