【问题标题】:What is the recommended approach for invalidating the cache on active_model_serializers 0.10.0?使 active_model_serializers 0.10.0 上的缓存失效的推荐方法是什么?
【发布时间】:2016-06-21 17:12:11
【问题描述】:

我在序列化程序级别使用缓存,这主要是完全按照我想要的方式工作(例如,模型的 updated_at 更改并且关联的序列化程序在缓存中失效)。

但是,在某些情况下,我需要能够手动定位特定的序列化程序并使其缓存无效。例如,我们目前正在构建一个问答功能,问题序列化程序包含 last_answer_at 和 answer_count。我希望尽可能长时间地缓存问题,因为它很少更改,但是如果创建新答案或删除现有答案,我希望能够定位相关问题并使其缓存无效。

我对此进行了一些调查,发现您可以通过以下方式获取缓存键:

serializer = QuestionSerializer.new(self)
adapter = ActiveModelSerializers::Adapter.create(serializer)
cache_key = serializer.cache_key(adapter)

但是,这不包括缓存键的属性部分。

我希望在这里实现的是父对象(在我的示例中为问题)将包含如下方法:

def clear_cache
  Rails.cache.clear(cache_key)
end

def cache_key
  serializer = QuestionSerializer.new(self)
  adapter = ActiveModelSerializers::Adapter.create(serializer)
  serializer.cache_key(adapter)
end

...在我的子对象中,在创建或删除答案时调用它。

after_create :clear_parent_cache

def clear_parent_cache
  question.clear_cache
end

有没有更好的方法来做到这一点?您能推荐一种始终获取正确缓存键的方法吗?

谢谢, 丹

注意:这也是 Github 存储库 (https://github.com/rails-api/active_model_serializers/issues/1816) 上的一个问题,在此处发布以确保它对更广泛的受众可见。

【问题讨论】:

    标签: ruby-on-rails caching active-model-serializers


    【解决方案1】:

    我认为这不是 AMS 的直接问题。

    有一个really nice RailsCast on this matter。仅引用要点:

    class Comment < ActiveRecord::Base
      belongs_to :article, :touch => true
    end
    

    将 :touch => true 添加到 belongs_to 关系意味着当评论被创建、更新或销毁时,它所属的文章被触及。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多