代码之家  ›  专栏  ›  技术社区  ›  Chowlett

从另一个模型更新对象时的缓存问题

  •  3
  • Chowlett  · 技术社区  · 16 年前

    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
    

    Foo 对象 value do_something

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

    ... 所以你应该做些什么 self 对象我能避免这个吗,除了移动 save! 他在附近吗?

    1 回复  |  直到 16 年前
        1
  •  2
  •   John Topley    16 年前

    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 方法,所以肯定有关联的缓存正在进行,这可以解释你看到的行为。在保存之前,您可能应该在其中一个方法中重新加载模型。

    推荐文章