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