Recipe 4.14. Storing Session Information in a Database


Problem

By default, Rails uses Ruby's PStore mechanism to maintain session information in the filesystem. However, your application may run across several web servers, complicating the use of a centralized filesystem-based solution. You want to change the default store from the filesystem to your database.

Solution

In environment.rb, update the session_store option by making sure it's set to :active_record_store and that the line is uncommented:

config/environment.rb:

Rails::Initializer.run do |config|   # Settings in config/environments/* take precedence to those specified here   config.action_controller.session_store = :active_record_store end  

Run the following rake command to create the session storage table in your database:

~/current$ rake create_sessions_table

Restart your web server for the changes to take effect.

Discussion

Rails offers several options for session data storage, each with its own strengths and weaknesses. The available options include: FileStore, MemoryStore, PStore (the Rails default), DRbStore, MemCacheStore, and ActiveRecordStore. The best solution for your application depends heavily on the amount of traffic you expect and your available resources. Benchmarking will ultimately tell you which option provides the best performance for your application. It's up to you to decide if the fastest solution (usually in-memory storage) is worth the resources that it requires.

The solution uses ActiveRecordStore, which is enabled in the Rails environment configuration file. rake's create_session_table task creates the database table that Rails needs to store the session details. If you'd like to reinitialize the session table, you can drop the current one with:

rake drop_sessions_table

Then recreate the table it with the rake command, and restart your web server.

The session table that rake creates looks like this:

mysql> desc sessions; +------------+--------------+------+-----+---------+----------------+ | Field      | Type         | Null | Key | Default | Extra          | +------------+--------------+------+-----+---------+----------------+ | id         | int(11)      |      | PRI | NULL    | auto_increment | | session_id | varchar(255) | YES  | MUL | NULL    |                | | data       | text         | YES  |     | NULL    |                | | updated_at | datetime     | YES  |     | NULL    |                | +------------+--------------+------+-----+---------+----------------+ 4 rows in set (0.02 sec) 

The following line fetches an Active Record User object and stores it in the session hash.

session['user'] = User.find_by_username_and_password('rorsini','elvinj')

You can use the debug helper function <%=debug(session) %> to view session output. A dump of the session hash shows the contents of the current session. Here's a fragment of the dump, showing the User object:

!ruby/object:CGI::Session  data: &id001    user: !ruby/object:User      attributes:        username: rorsini       id: "1"        first_name: Rob       password: elvinj       last_name: Orsini

The same session record can be viewed directly in the sessions table, but the serialized data will be unreadable. The updated_at field can be helpful if you find the sessions table getting large. You can use that date field to remove sessions that are more than a certain age and thus no longer valid.

mysql> select * from sessions\G *************************** 1. row ***************************         id: 1 session_id: f61da28de115cf7f19c1d96beed4b960       data: BAh7ByIJdXNlcm86CVVzZXIGOhBAYXR0cmlidXRlc3sKIg11c2VybmFtZSIM cm9yc2luaSIHaWQiBjEiD2ZpcnN0X25hbWUiCFJvYiINcGFzc3dvcmQiC2Vs dmluaiIObGFzdF9uYW1lIgtPcnNpbmkiCmZsYXNoSUM6J0FjdGlvbkNvbnRy b2xsZXI6OkZsYXNoOjpGbGFzaEhhc2h7AAY6CkB1c2VkewA=  updated_at: 2006-01-04 22:33:58 1 row in set (0.00 sec)

See Also

  • Section 4.15"




Rails Cookbook
Rails Cookbook (Cookbooks (OReilly))
ISBN: 0596527314
EAN: 2147483647
Year: 2007
Pages: 250
Authors: Rob Orsini

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net