ruby-on-rails - 私有(private)方法中的 HGET 不返回哈希

标签 ruby-on-rails ruby redis

由于某种原因,我的 hget 没有找到或返回我在公共(public)方法中设置的散列。我不明白为什么。

这一切都在一个继承自 ApplicationController 的 Controller 中,这是我定义我的 redis 初始化程序的地方:

def redis
   Thread.current[:redis] ||= Redis.new
end

然后在我的 Controller 中我这样做来设置散列:

def return_customer
  email = params["email"]
  customer = Customer.find_by(email: email)
  credit_amount = customer.credit_amount.to_f
  customer_data = {email: email, customer_id: customer.id, credit_amount: credit_amount}
  redis.hset("shop:#{customer.shop.id}:customer", customer_data, customer_data.inspect)
  render json: customer
end

然后我终于有了在同一个 Controller 中的其他方法中使用的这个私有(private)方法,这是不起作用的部分:

private

def get_customer_from_redis
  shop = Shop.find_by(shopify_domain: params["shop"])
  customer_info = redis.hget("shop:#{shop.id}:customer", customer_data)
  eval(customer_info)
end

这是返回的错误

TypeError (no implicit conversion of nil into String):

最佳答案

我建议您不要使用 .inspect,而是像这样使用 .to_json:

def return_customer
  email = params["email"]
  customer = Customer.find_by(email: email)
  credit_amount = customer.credit_amount.to_f
  customer_data = {email: email, customer_id: customer.id, credit_amount: credit_amount}
  redis.set("shop:#{customer.shop.id}:customer", customer_data.to_json)
  render json: customer
end

然后在你的私有(private)方法中

def get_customer_from_redis
  shop = Shop.find_by(shopify_domain: params["shop"])
  customer_info = redis.get("shop:#{shop.id}:customer", customer_data)
  JSON.parse(customer_info) if customer_info
end

关于ruby-on-rails - 私有(private)方法中的 HGET 不返回哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44006286/

相关文章:

ruby -/usr/bin/jekyll : No such file or directory

redis - Redis 在 Trello 中是如何使用的?

performance - 可能在 redis 中使用 lua 将存储在集合中的所有 key 作为哈希列表返回?

ruby-on-rails - Redis 计数器始终关闭

ruby-on-rails - 橡胶无法用于Rails AWS部署

ruby-on-rails - 使用Delayed::Job时使用ActiveJob设置优先级

php - redis pub/sub 在 php 中是否现实?

javascript - rails : Using Jquery for Text_Area character count

ruby - 对包含字符串和整数的字符串进行排序,使字符串按字母顺序排列,所有整数按顺序排列

ruby-on-rails - 在 Rails 中渲染 PNG 文件