本文介绍了最好的方式(除了会话)在Rails控制器中存储对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个rails控制器

I have a rails controller

class Controllername < application
  def method1
    obj = API_CALL
    session =obj.access_token 
     redirect_to redirect_url    #calls the API authorization end point 
                            #and redirects to action method2  
  end
  def method2    
    obj.call_after_sometime
  end
end

我在method1中调用一些API获取对象并在会话中存储访问令牌和秘密。 method1 完成它的动作。

I am calling some API's in method1 getting a object and storing access token and secrets in a session. method1 finishes it's action.

过了一段时间,我调用 method2

After sometime I am calling method2, now the session(access token, secrets) is stored correctly.

但现在在 method2 I需要使用OBJECT obj .But,现在 obj call_after_sometime c $ c>不可用,因为我没有将它存储在会话中(我们将收到加密对象存储的SSL错误)。

But, now inside method2 I need to call the API call_after_sometime using the OBJECT obj.But, now obj is unavailable because I didn't store it in a session(We will get a SSL error storing encrypted objects).

我想知道什么是最好的方法来存储 method1 中的 obj ,以便稍后可以在 method2

I want to know what's the best way to store obj in method1 so that it can be used later in method2

编辑:

当我尝试Rails.cache或会话我得到错误

when I tried Rails.cache or Session I am getting the error

 TypeError - no _dump_data is defined for class OpenSSL::X509::Certificate

当我在会话中存储加密的值时,我发现它会抛出此错误。

Googling it I found when I store encrypted values in session it will throw this error.

推荐答案

您可以尝试缓存它,但要注意缓存键,如果对象对于每个用户是唯一的,那么在缓存键中添加用户ID

You can try caching it, but be careful of the caching key, if the object is unique per user then add the user id in the caching key

class Controllername < application
  def method1
    obj = API_CALL
    Rails.cache.write("some_api_namespace/#{current_user.id}", obj)
    session =obj.access_token 
  end
  def method2
    obj = Rails.cache.read("some_api_namespace/#{current_user.id}")
    obj.call_after_sometime
  end
end

如果在尝试读取缓存时可能不存在缓存,那么可以使用 fetch 而不是读取,如果没有找到数据,将调用api

If there's a possibility that the cache might not be existent when you try to read it, then you could use fetch instead of read which will call the api if it doesn't find the data

def method2
  obj = Rails.cache.fetch("some_api_namespace/#{current_user.id}") do
    method_1
  end
  obj.call_after_sometime
end

和我还

这篇关于最好的方式(除了会话)在Rails控制器中存储对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 13:42