How do I get a session id?

I'm a bit of a newbie, but I'll try to help...

I have a model containing

    class User < ActiveRecord::Base

and I set the session ID in a controller with

  def login     session[:user_id] = nil     if       user = User.authenticate(params[:name], params[:password])       if user         session[:user_id] =         ...

and I retrieve it in a view as e.g.

    User id: <%= session[:user_id] %>

and all of this is copied from Thomas et al. Agile Web Develoopment with Rails (version 2), a book that I recommend highly.

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]


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?


Alex MacCaw wrote:

Well, I would reply to my own last email, but google can be hella slow accepting mail...

Anyway, you're gonna laugh:


Sometimes it's better to just try something in the code than to search for it. :slight_smile:


Alex MacCaw wrote: