私有方法中的HGET不返回哈希

时间:2017-05-16 15:59:28

标签: ruby-on-rails ruby redis

某些原因我的hget没有找到或返回我在公共方法中设置的哈希值。我无法弄清楚原因。

这是一个继承自ApplicationController的控制器,这是我定义redis初始值设定项的地方:

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

然后在我的控制器中我这样做来设置哈希:

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

然后最后我在同一个控制器中的其他方法中使用了这个私有方法,这是不起作用的部分:

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):

1 个答案:

答案 0 :(得分:1)

我建议你而不是像.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

然后在你的私人方法中

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