Cache issues when updating an object from another model

I had a problem making changes to an object from another model, as well as to the object model. I have the following models:

class Foo < ActiveRecord::Base
  has_many :bars

  def do_something
    self.value -= 1
    # Complicated code doing other things to this Foo

    bars[0].do_other

    save!
  end
end

class Bar < ActiveRecord::Base
  belongs_to :foo

  def do_other
    foo.value += 2
    foo.save!
  end
end

If I have an object Fooc valueset to 1 and call do_somethingon it, I can see the following two operations from my database logs:

Foo Update (0.0s) UPDATE "foos" SET "value" = 2 WHERE "id" = 1
Foo Update (0.0s) UPDATE "foos" SET "value" = 0 WHERE "id" = 1

... therefore do_something supposedly caches the object self. Can I avoid this except by moving save!around?

+3
source share
1 answer

ActiveRecord reload . :

# File vendor/rails/activerecord/lib/active_record/base.rb, line 2687
def reload(options = nil)
  clear_aggregation_cache
  clear_association_cache
  @attributes.update(self.class.find(self.id, options).instance_variable_get('@attributes'))
  @attributes_cache = {}
  self
end

— , clear_association_cache, , , . , .

+2

Source: https://habr.com/ru/post/1733868/


All Articles