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..
5 Answers
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!
-
1For database-based sessions (which you should probably use) you can expire through a query: guides.rubyonrails.org/security.html#session-expiry– m33lkyFeb 24, 2012 at 7:14
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.
-
Anybody have any thoughts on the merits of this method vs the one recommended by Gdeglin? Jan 16, 2014 at 17:00
-
3This can be used when you want to retain other parameters but delete one particular key value pair.– LavixuJan 17, 2014 at 5:59
-
2This will not reset the session at all, it will assign a local variable. Never use this technique to reset the session: session = {} Feb 4, 2014 at 13:38
-
4The Rails documentation, on section 5.1 Accessing the Session recommends to use reset_session if you want remove script-inserted key/value pairs (ex: Something inserted from a controller) and generate a new session. If you want reset only the key/value pairs you set, set those keys to nil.– sargasApr 24, 2014 at 22:33
-
1@barlop It looks like you're probably better off using
reset_session
, as it does some other cleaning up beyond whatsession.clear
does. Internally,reset_session
callssession.destroy
, which itself callsclear
as well some other stuff.– lobatiJul 3, 2018 at 16:23
to delete a user's session
session.delete(:user_id)
-
-
3@Arthur That's not true. But you'll only delete the :user_id key from the session and not the whole session– AndiónMar 6, 2018 at 12:05
To clear only certain parameters, you can use:
[:param1, :param2, :param3].each { |k| session.delete(k) }
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
-
I find that
@_request.reset_session
andreset_session
both work and maybe do the same thing?– barlopJul 3, 2018 at 9:09