How to empty/destroy a session in rails?

痞子三分冷 提交于 2019-12-17 10:17:47

问题


I can't seem to find it anywhere... How do I delete/destroy/reset/empty/clear a user's session in Rails? Not just one value but the whole thing..


回答1:


To clear the whole thing use the reset_session method in a controller.

reset_session

Here's the documentation on this method: http://api.rubyonrails.org/classes/ActionController/Base.html#M000668

Resets the session by clearing out all the objects stored within and initializing a new session object.

Good luck!




回答2:


session in rails is a hash object. Hence any function available for clearing hash will work with sessions.

session.clear

or if specific keys have to be destroyed:

session.delete(key)

Tested in rails 3.2

added

People have mentioned by session={} is a bad idea. Regarding session.clear, Lobati comments- It looks like you're probably better off using reset_session [than session.clear], as it does some other cleaning up beyond what session.clear does. Internally, reset_session calls session.destroy, which itself calls clear as well some other stuff.




回答3:


To clear only certain parameters, you can use:

[:param1, :param2, :param3].each { |k| session.delete(k) }



回答4:


to delete a user's session

session.delete(:user_id)



回答5:


add this code to your ApplicationController

def reset_session
  @_request.reset_session
end

( Dont know why no one above just mention this code as it fixed my problem ) http://apidock.com/rails/ActionController/RackDelegation/reset_session



来源:https://stackoverflow.com/questions/2405635/how-to-empty-destroy-a-session-in-rails

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