我有一个 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 获取对象并在 session 中存储访问 token 和 secret 。 method1
完成它的 Action 。
一段时间后,我调用了 method2
,现在 session (访问 token 、 secret )已正确存储。
但是,现在在 method2
中,我需要使用 OBJECT obj
调用 API call_after_sometime
。但是,现在 obj
不可用,因为我没有将它存储在 session 中(我们将在存储加密对象时遇到 SSL 错误)。
我想知道在 method1
中存储 obj
的最佳方式是什么,以便稍后在 method2
中使用它
编辑:
当我尝试 Rails.cache 或 Session 时出现错误
TypeError - no _dump_data is defined for class OpenSSL::X509::Certificate
谷歌搜索我发现当我在 session 中存储加密值时它会抛出这个错误。
最佳答案
您可以尝试缓存它,但要注意缓存键,如果每个用户的对象都是唯一的,则将用户 ID 添加到缓存键中
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
而不是 read
如果它会调用 api没有找到数据
def method2
obj = Rails.cache.fetch("some_api_namespace/#{current_user.id}") do
method_1
end
obj.call_after_sometime
end
关于ruby-on-rails - 在 Rails Controller 中存储对象的最佳方式( session 除外)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30119531/