Best way (other than session) to store objects in Rails controller?

谁说胖子不能爱 提交于 2019-12-07 10:54:40

问题


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

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.

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

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

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

EDIT:

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.


回答1:


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

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

more info here and I also wrote about it here




回答2:


Try this: write obj into a key in the session and read it out again in the second method.

class Controllername < application
  def method1
    obj = API_CALL
    session[:obj] = obj
  end
  def method2    
    if obj = session[:obj]
      obj.call_after_sometime
    end
  end
end


来源:https://stackoverflow.com/questions/30119531/best-way-other-than-session-to-store-objects-in-rails-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!