Reputation: 4280
Ok, there appears to be few approaches to 'destroying' a user's session and there may be subtleties between them and how the app handles user sessions.
First, why is it most examples don't use session.delete(:current_user_id)
to delete the :current_user_id
value (and its hash key!)? A typical example looks like the below (I added deleting :return_to
since if signing out, why would there by a need to track a return_to value).
def sign_out
self.current_user = nil
session[:current_user_id] = nil
session.delete(:return_to)
end
If the app needs to delete all session variables and values, isn't it safer to simply use session = nil
or session.destroy
? This will destroy the hash entirely. It would make sense to keep current_user_id
in your session hash if your app supports... say tracking of anonymous users ?!?!
Thoughts?
Upvotes: 0
Views: 347
Reputation: 17647
The proper way to do this is to use the rails method reset_session. If you want to persist certain portion of the session, I would use something like this in your application controller:
def reset_session_with_persistence(*keys_to_persist)
persisted_flash = flash
persisted_keys = keys_to_persist.inject({}) { |keys, key| keys.merge( { key => session[key] } ) }
reset_session
persisted_flash.each { |key, value| flash[key] = value }
keys_to_persist.each { |key_to_persist| session[key_to_persist] = persisted_keys[key_to_persist] }
end
Upvotes: 0
Reputation: 766
By setting session to nil you're losing all the information about session (that may also be included except current_user or used by Rails) + you are putting yourself into risk of using a hash method (like #[]) on nil which will raise you exception where you won't expect it.
Upvotes: 0