128
session[:message] = nil

Is this is the best way to destroy a session variable.

Note: I don't want to clear all the session variables like reset_session does.

ndnenkov
  • 35,425
  • 9
  • 72
  • 104
Mohit Jain
  • 43,139
  • 57
  • 169
  • 274

1 Answers1

261
session.delete(:message)

In general, session variable is SessionHash object, which is inherited from hash.

ndnenkov
  • 35,425
  • 9
  • 72
  • 104
Sigurd
  • 7,865
  • 3
  • 24
  • 34
  • 16
    This is the correct way to do it. session[:message] = nil will leave the :message key in the session hash, this will destroy the key and value, as if your session never had any value assigned to that key. – Brett Bender Oct 22 '10 at 17:22
  • 1
    @BrettBender is this still true for rails 6? thanks for your help! – Crashalot Dec 26 '20 at 09:19
  • Sorry, no idea, I haven't used ruby / rails in a long time (Rails 4). This comment is over a decade old! :P – Brett Bender Feb 03 '21 at 18:09
  • 1
    @Crashalot this is still valid for Rails 6 according to the Ruby on Rails Guides (v6.1.4): https://guides.rubyonrails.org/action_controller_overview.html#accessing-the-session – nico_lrx Sep 02 '21 at 13:35