Rails association callback with cached query

时间:2016-04-15 11:16:10

标签: ruby-on-rails ruby-on-rails-4 activerecord ruby-on-rails-3.2

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.

1 个答案:

答案 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