Jamal Soueidan wrote the following on 07.03.2007 11:21 :
I would rather put all the information in the session, so I get receive
what I need like this
session[:user][:id]
session[:user][:username]
etc.
this way I don't need to connect to the database everytime I need other
information about the uesr
This is premature optimization and has several limitations (like not
being able to see modifications to the data you cache in the session and
more overhead if you use the ActiveRecord session store). From your
example above, I suspect you may not be able to treat session[:user]
like a full bown ActiveRecord::Base derived class. You won't be able to
use the new CookieStore for the sessions if you store too much data in
them (which is by the way faster than ActiveRecord or Pstore and doesn't
need an external process like the Memcache store).
I use this when I need to access the current user and only store its id
in session[:user_id].
def current_user
# Cache the User instance (probably used multiple times in a request)
return @cached_user if @cached_user
session[:user_id] ? (@cached_user = User.find(:first,
:conditions => [
'id = ?', session[:user_id]])) : nil
end
Avoid hitting several time the database for the same data in a single
request, but don't get in the way if the data has been modified behind
your back.
If you really need to avoid database access, you can use acts_as_cached
or CachedModel for your users without the drawbacks of explicitely
caching them in the session...
Wish someone would answer your actual question... I've scoured the docs and google and can't find anything about getting the session id. That's something I used to do fairly often in Java, but I haven't actually needed it in rails yet. Why do you need the session id?