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

此生再无相见时 提交于 2019-12-05 15:40:02

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

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