我在我的应用程序中使用 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/