# problem with nil.user

**URL:** <https://discuss.rubyonrails.org/t/problem-with-nil-user/42080>\
**Category:** rubyonrails-talk\
**Created:** [April 29, 2009, 8:30pm UTC](https://discuss.rubyonrails.org/t/problem-with-nil-user/42080 "2009-04-29T20:30:16Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Rick3](https://avatars.discourse-cdn.com/v4/letter/r/ecb155/32.png) [@Rick3](https://discuss.rubyonrails.org/u/Rick3)\
**Post date:** [April 29, 2009, 8:30pm UTC](https://discuss.rubyonrails.org/t/problem-with-nil-user/42080/1 "2009-04-29T20:30:16Z")

</div>

Try

def is\_logged\_in? &nbsp;&nbsp;@logged\_in\_user = User.find(session[:user]) if session[:user] end

---

<div class="post-metadata">

**Author:** ![11175](https://avatars.discourse-cdn.com/v4/letter/1/8edcca/32.png) [@11175](https://discuss.rubyonrails.org/u/11175)\
**Post date:** [April 29, 2009, 9:10pm UTC](https://discuss.rubyonrails.org/t/problem-with-nil-user/42080/2 "2009-04-29T21:10:03Z")

</div>

Rick Lloyd wrote:

> Try
> 
> def is\_logged\_in? &nbsp;&nbsp;@logged\_in\_user = User.find(session[:user]) if session[:user] end
> 
> On Apr 29, 10:15�am, Stephen Fagan \<rails-mailing-l...@andreas-s.net\>

Thanks Rick. It worked a treat and also opened up a couple of gaping holes aswell (which I've managed to rectify!)

Cheers

Stephen.

---

<div class="post-metadata">

**Author:** ![Jeff\_Burly](https://avatars.discourse-cdn.com/v4/letter/j/c68b51/32.png) [@Jeff\_Burly](https://discuss.rubyonrails.org/u/Jeff_Burly)\
**Post date:** [April 29, 2009, 9:26pm UTC](https://discuss.rubyonrails.org/t/problem-with-nil-user/42080/3 "2009-04-29T21:26:04Z")

</div>

Just to followup if you're interested, .... the error msg from the op was due to the fact that the call to session[:user\_id] returned nil, and thus calling find(nil) resulted in that error being raised. If you wanted to avoid such an error and just have the find call return nil if not found, one way is to just call find\_by\_id:

$ ./script/console

> > u = User.find(nil)

ActiveRecord::RecordNotFound: Couldn't find User without an ID &nbsp;&nbsp;from /usr/lib/ruby/... &nbsp;&nbsp;...

> > u = User.find\_by\_id(nil)

=\> nil

Jeff
