Norm Scherer wrote in post #1102294:
> On 03/18/2013 10:37 AM, John Merlino wrote:
>> Is there a good practice when to use the session variable. Sometimes I
>> find myself using both the session variable and instance variable. For
>> example, I have a table that allows a user to select a date. I store
>> the date both in the session and in the instance variable. Should I
>> not bother to store it in session? In what situations should you use
>> the session variable? --
> The rails session persists across requests while instance variables do
> not.  If you need something in a following request it (or a reference)
> must be in the session.  If you do not need it later I always use an
> instance variable.

I wouldn't say that this is precisely accurate. You could continue 
passing a variable from one request to another, and to third, and so on.

Session variables are useful when you really need a value to persist for 
the entire session. I would also say that it's good practice to use 
session variable sparingly. Session variables are somewhat akin to 
global variables in the sense that they represent globally accessible 
shared state (at least within the context of the current session).

Session variables are also long lived, taking up memory as long as the 
session is kept alive. Although in a Rails application sessions are torn 
down and recreate upon every request, but that might even be worse than 
just leaving them in memory between requests.

Another thing to keep in mind is that by default Rails uses a cookie 
based session storage mechanism, which means sessions have a hard 4K 
limit (cookies are limited to 4K by spec). Another reason to avoid 
putting large amounts of data in the session.

A typical use case for session variable are things like the "id" of the 
current user. Notice I said the "id" not the user object itself. It's 
better to load the user object when, and only when, necessary. There are 
other great uses for session variables, but think twice about if it's 
really necessary and try to keep the amount of data as small as 
possible. Remember for every variable in the session is just one more 
thing that has to be loaded from persistent storage on every single 
request.

-- 
Posted via http://www.ruby-forum.com/.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to