Using ActiveRecord to store session information in Ruby on Rails
Rails default setting is to store sessions on the file system. This is fine during development, but this is not very scalable once an application goes into production. Often the application will be deployed to a number of servers. One good solution to is to use ActiveRecord to store the session information in the database. Fortunately this is very easy to do!
First of, open the config/environments.rb file and uncomment the following line:
config.action_controller.session_store = :active_record_store
Now we create the sessions table. There is already a rake task for doing this:
rake db:sessions:create
rake db:migrate
Now restart your server and voila! Rails does not automatically manage sessions so it is worth noting that you will need to deal with this. If you do not you could end up with a sessions table with millions of rows. This will slow your application down considerably. I will post more information soon on sweepers and dealing with session expiry.
Trackbacks
Use this link to trackback from your own site.
Nice article.
How do you create a sweeper for this?
I’m new to this. All I know is that sweepers are normally for expiring page/action/fragment caches. They observe models.
Perhaps I need to create an hourly task with crontab?
Hi Xin,
Sorry if that last sentence is a little misleading. Sweepers are for cache expiry. I am intending on posting about sweepers (for cache expiry) and about session expiry soon.
I suppose you could use sweepers to expire session data if it was stored as flat files rather than using activerecord, but it would be quite ugly. I think there are far better solutions.
Matt
Django handles session data by storing it in the DB by default. You may want to have a browse through their code to get some ideas for implementations - expiration solutions etc.
Any idea on how to do this onto a separate db?