本文介绍了在 Rails 应用程序上将 HASH 保存到 Redis的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用带有 Rails 的 Redis,所以这可能是一个愚蠢的问题.

Im just starting off with Redis with Rails so this maybe a dumb question.

我正在尝试将哈希保存到 redis 服务器,但是当我检索它时它只是一个字符串 IE.

I am trying to save a hash to redis server but when I retrieve it its just a string IE.

hash = {"field" => "value", "field2" => "value2"}
$redis.set('data', hash)

#So collecting the data
@data = $redis.get('data')

这显然是错误的,因为它以字符串形式返回.

This is obviously wrong as its returning as a string.

我也尝试过循环一些结果并使用 hset ie.

I have also tried looping some results and using the hset ie.

@data.each do |d|
  $redis.hset('data', d.field, d.value)
end

# errror
# ERR Operation against a key holding the wrong kind of value

不知道去哪里.我已经删除了密钥 $redis.del('data') 以确保这不是问题.

Not sure where to go. I have deleted the key $redis.del('data') to make sure that was not the issue.

希望你能给我建议,李

推荐答案

我应该更彻底地阅读 redis 文档.

I should have read the redis docs more thorough.

答案:

IN
$redis.set 'data', hash.to_json

OUT
data = JSON.parse($redis.get("data"))

这篇关于在 Rails 应用程序上将 HASH 保存到 Redis的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 05:12