tybro0103
tybro0103

Reputation: 49703

How to empty/destroy a session in rails?

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

Upvotes: 156

Views: 135595

Answers (5)

Lavixu
Lavixu

Reputation: 1398

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.

Upvotes: 52

David Mesaros
David Mesaros

Reputation: 71

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

Upvotes: 5

vjnan369
vjnan369

Reputation: 853

to delete a user's session

session.delete(:user_id)

Upvotes: 11

vladCovaliov
vladCovaliov

Reputation: 4403

To clear only certain parameters, you can use:

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

Upvotes: 5

Gdeglin
Gdeglin

Reputation: 12618

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!

Upvotes: 223

Related Questions