我喜歡觀察添加一個對象到我的has_many關係而不將它們保存到數據庫。
因此,當我添加一個LineItem到我的訂單中時,我喜歡調用Order :: calculate_total來更新實際的總價值。觀察積極記錄關係
o = Order.new
o.line_items << LineItem.new # should call calculate_total from order-object
但也有我的LineItem的積累方法沒有觀察員。
我喜歡觀察添加一個對象到我的has_many關係而不將它們保存到數據庫。
因此,當我添加一個LineItem到我的訂單中時,我喜歡調用Order :: calculate_total來更新實際的總價值。觀察積極記錄關係
o = Order.new
o.line_items << LineItem.new # should call calculate_total from order-object
但也有我的LineItem的積累方法沒有觀察員。
我收回自己。我剛剛發現了關聯回調:ActiveRecord::Associtions::ClassMethods,搜索「關聯回調」。實質上:
class Order < ActiveRecord::Base
has_many :line_items, :after_add => :calculate_order_total
end
您還可以訪問before_add,before_remove和after_remove。
採取不同的方式:
class Order < ActiveRecord::Base
def add_line_item(line_item)
self.line_items << line_item
self.calculate_total
end
end
但我質疑爲什麼你需要計算總在每個行項目的補充。如果您在添加所有訂單項後只計算一次,則可以實現同樣的效果。
ok,這樣我就會失去使用我的訂單模型的Active-record-way - 我必須確保沒有人使用<< operator或order.line_items.build()。 我的想法是使用觀察者將涵蓋line_item添加到訂單的所有方式。 如果您看到像購物車一樣訂購,則用戶希望看到他將產品放入購物車中的總增加時間。所以必須在每條line_item上完成。 – toy 2010-02-19 15:42:04
不錯,那是我失蹤的那個! – toy 2010-02-19 16:41:38