加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在Rails控制器中存储对象的最佳方式(会话除外)

发布时间:2020-12-17 02:48:23 所属栏目:百科 来源:网络整理
导读:我有一个导轨控制器 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_someti
我有一个导轨控制器

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

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

一段时间后我调用method2,现在会话(访问令牌,秘密)被正确存储.

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

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

编辑:

当我尝试Rails.cache或Session我收到错误

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

谷歌搜索我发现当我在会话中存储加密值时,它会抛出此错误.

解决方法

您可以尝试缓存它,但要小心缓存键,如果对象是每个用户唯一的,那么在缓存键中添加用户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

more info here和我也是wrote about it here

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读