views:

41

answers:

2

hi Stack,
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.

A: 

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.

François Beausoleil
ok, that way I would loose the Active-record-way of using my order-model - I would have to make sure that nobody uses the << operator or order.line_items.build() . My thoughts were using an observer would cover all ways a line_item were added to the order.if you see Order like a cart the user wants to see the total rise evertime he puts a Product in the cart. so it has to be done on every line_item.
toy
+1  A: 

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.

François Beausoleil
nice, that's the one I was missing!
toy
Could you accept the answer then?
François Beausoleil