ruby-on-rails - 如何防止在 Rails 缓存中存储 nil 值?

标签 ruby-on-rails ruby-on-rails-3 caching memcached

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

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

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

最佳答案

您可以在 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

然后使用:
Rails.cache.fetch_no_nil{"user_by_comment_id:#{params['comment_id']}"} do
 User.find_by_comment_id(params['comment_id'])
end

关于ruby-on-rails - 如何防止在 Rails 缓存中存储 nil 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17485525/

相关文章:

ruby-on-rails - 在 Rails 3 中,如何在请求/响应周期完成后通过 Controller 调用一些代码?

ruby-on-rails - Controller 中的 attr_accessor 用于存储权限

ruby-on-rails-3 - 如何在 Rails 3 的占位符中使用 <br/>?

c# - 为什么在从字典中读取时锁定

android - WebView 内存不足异常

ruby-on-rails - Rails 在数据库中将我的属性设置为 nil

ruby-on-rails - Rails 6 - Heroku 上的 InvalidAuthenticityToken

ipad - HTML5 缓存大小?

ruby-on-rails-3 - response_with 正在询问错误时的位置

ruby-on-rails - Rails : validate presence of foo unless bar == 'baz'