如何防止在 Rails 缓存中存储 nil 值?

Ach*_*ius 10 memcached caching ruby-on-rails ruby-on-rails-3

我在我的应用程序中使用 redis-store 进行缓存,如果值返回 nil,我不想获取键和值。

Rails.cache.fetch{"user_by_comment_id:#{params['comment_id']}"} do
 User.find_by_comment_id(params['comment_id'])
end
Run Code Online (Sandbox Code Playgroud)

如果它返回键“user_by_comment_id:#{params['comment_id']}”的 nil,我不想将密钥存储在我的缓存中。帮我解决这个问题。

Van*_*tin 15

更新:

从rails 6.0.0开始,您可以skip_nil: true在调用时提供选项Rails.cache.fetch

这里

感谢里克·萨格斯指出了这一点。


Suc*_*oir 4

您可以在 Rails.cache 类中添加方法来处理您的情况(将该代码放在初始化程序中的某处):

   module ActiveSupport
   module Cache
    class Store
      def fetch_no_nil(name, options = nil)
        if block_given?
          options = merged_options(options)
          key = namespaced_key(name, options)

          cached_entry = find_cached_entry(key, name, options) unless options[:force]
          entry = handle_expired_entry(cached_entry, key, options)

          if entry
            get_entry_value(entry, name, options)
          else
            save_block_result_to_cache_if_not_nil(name, options) { |_name| yield _name }
          end
        else
          read(name, options)
        end
      end
      private
      def save_block_result_to_cache_if_not_nil(name, options)
        result = instrument(:generate, name, options) do |payload|
          yield(name)
        end
        write(name, result, options) unless result.nil?
        result
      end
    end
  end
  end
Run Code Online (Sandbox Code Playgroud)

然后使用:

Rails.cache.fetch_no_nil{"user_by_comment_id:#{params['comment_id']}"} do
 User.find_by_comment_id(params['comment_id'])
end
Run Code Online (Sandbox Code Playgroud)