8

我在我的应用程序中使用 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,我不想将键存储在我的缓存中。帮我解决这个问题。

4

2 回答 2

10

更新:

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

这里

感谢Rick Suggs指出这一点。

于 2019-08-16T18:38:02.980 回答
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

然后使用:

Rails.cache.fetch_no_nil{"user_by_comment_id:#{params['comment_id']}"} do
 User.find_by_comment_id(params['comment_id'])
end
于 2013-07-05T12:55:57.500 回答