I have two models:
class Basket < ActiveRecord::Base
has_many :products
def recalculate_price!
price = products.map(&:price).sum
save
end
end
class Product < ActiveRecord::Base
belongs_to :basket
after_save :update_basket
def update_basket
basket.recalculate_price!
end
end
and than I call it like this:
basket = Basket.new
basket.products.build(price)
basket.save
The problem: basket.price
don't update.
I've investigated the problem and found out that there is some kind of caching in update_basket
method. The problem could be solved with placing reload
before basket.recalculate_price!
.
Is there any option to leave the update_basket
method untouched? I have many such cases in my application.
I would like to understand how it works and avoid similar problems in the future.
note: I recently upgraded rails from 3.2 to 4.2. In a previous version everything worked fine.
答案 0 :(得分:1)
是否有任何选项可以保持update_basket方法不受影响?
绝对。您可以在after_create
上放置一个条件,以避免执行某些条件:
after_save :update_basket if: :basked_should_be_updated
[...]
private
def basked_should_be_updated
[...]
# return true or false in here
end