# Disabling session when user is not logged in

**URL:** <https://www.ruby-forum.com/t/disabling-session-when-user-is-not-logged-in/130426>\
**Category:** Rails\
**Created:** [February 28, 2008, 4:56am UTC](https://www.ruby-forum.com/t/disabling-session-when-user-is-not-logged-in/130426 "2008-02-28T04:56:49Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![josh](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/45deac/32.png) [@josh](https://www.ruby-forum.com/u/josh)\
**Post date:** [February 28, 2008, 4:56am UTC](https://www.ruby-forum.com/t/disabling-session-when-user-is-not-logged-in/130426/1 "2008-02-28T04:56:49Z")

</div>

I would like to avoid creating sessions for users who are not logged  
in. To that end, I have added the following to my  
ApplicationController:

session :off, :if =\> Proc.new { |req| req.session[:user\_id].nil? }

Based on my understanding, if the Proc returns true (e.g.  
session[:user\_id] is null), a session will not be created. This does  
not seem to be working though as a session is always created in the  
DB. Any thoughts?

Thanks,  
Josh

---

<div class="post-metadata">

**Author:** ![josh](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/45deac/32.png) [@josh](https://www.ruby-forum.com/u/josh)\
**Post date:** [February 28, 2008, 12:52pm UTC](https://www.ruby-forum.com/t/disabling-session-when-user-is-not-logged-in/130426/2 "2008-02-28T12:52:11Z")

</div>

On 28 Feb 2008, at 03:56, Josh wrote:

> I would like to avoid creating sessions for users who are not logged  
> in. To that end, I have added the following to my  
> ApplicationController:
> 
> session :off, :if =\> Proc.new { |req| req.session[:user\_id].nil? }

I think the problem here is that you are accessing the request  
session, which in turn causes a session to be created.  
You need a way to say “give me the session if it exists, but if it  
doesn’t exist don’t bother”. A cursory glance at the source  
(cgi\_process.rb is the interesting file suggests that there is no api  
for this and you’ll just have to look for the presence of an @session  
instance variable in the request object.

Fred

---

<div class="post-metadata">

**Author:** ![josh](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/45deac/32.png) [@josh](https://www.ruby-forum.com/u/josh)\
**Post date:** [February 28, 2008, 8:00pm UTC](https://www.ruby-forum.com/t/disabling-session-when-user-is-not-logged-in/130426/3 "2008-02-28T20:00:04Z")

</div>

Thanks Fred, that did seem to be part of the problem.

Now, the trick is initializing the session when I need it in my  
SessionController#new action. Any thoughts? Can I just initialize a  
new CgiSession here?

Updated code:

session :off, :if =\> Proc.new { |req| !session\_exists?(req) }

private  
class \<\< self  
def session\_exists?(request)  
request.instance\_variable\_defined?(:@session)  
end  
end
