由于某种原因,我的 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/