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 << Line开发者_Go百科Item.new # should call calculate_total from order-object
but there are no observers for the build-method of my LineItem.
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.
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.
精彩评论