When someone visits my train schedule site, he enters a “from station”, a “to station”, and then submits the form to get the schedule.
I want the site to remember the user’s last choice of from / to station when he next visits the site. Here’s my current strategy:
In my index action (the action corresponding to the root URL):
def index
to_station = "Grand Central Terminal"
from_station = ""
if session[:from_station]
from_station = session[:from_station]
end
if session[:to_station]
to_station = session[:to_station]
end
@schedule = Schedule.new(:to_station => to_station, :from_station => from_station)
end
In my show action (the action that shows the actual train schedule):
def show
@schedule = Schedule.new(params[:schedule])
if @schedule.trains
session[:from_station] = @schedule.from_station
session[:to_station] = @schedule.to_station
render :partial => 'table', :locals => { :schedule => @schedule }
else
render :partial => 'error', :locals => { :schedule => @schedule }
end
end
And in my ApplicationController:
session :session_expires => 1.year.from_now
Is this the right approach? In particular, is session :session_expires => 1.year.from_now the “right” way to make the session (and by extension the user’s choice of stations) last for a “long time”?
You should use cookies
The first reason for this is that storing the data in session means that the data is stored in yuor server’s memory. Eventually, with you keeping that data in memory for such large amounts of time, you memory will get full
The second reason is that if you need to restart your server (or some something that requires the apache/iis/ror/web hosting service to be restarted) session data will be cleared. Session is typically for short term data storage.
Now there are such things as SqlSessionStores (eg http://railsexpress.de/blog/articles/2005/12/19/roll-your-own-sql-session-store) so you could store your session data for much longer, without the limitation of server memory filling up and without the limitation of lossing all session data if you restart your server. However be warned that these are still designed for short term storage, I wouldn’t use them for long term storage.
Cookie – Kept until user clears cookies in browser, or until cookie expires; long term non-critical storage
Session – Kept until user clears cookies in browser (cookies are used to track a user and identify their session), or web service/server restarts, or session expires; short term non-critical storage
SqlSession – Kept until user clears cookies in browser, or session expires; short term non-critical storage