Rails 3: Storing Session in Active Record (not cookie)

Viewed 12382

I trawled google university for about an hour or so but there is no single good documentation on this topic :-( Hoping someone can help. I am willing to buy a book as well as long as someone can tell me which one.

I am using following versions:

  • rails 3.2.6,
  • ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-darwin11.4.0]

To start using session storage in Active Record instead of cookie, I did following:

  1. Update config/initializers/session_store.rb. Commented first line and uncommented the last one, so I have:

    # Be sure to restart your server when you modify this file.
    
    # Myapp::Application.config.session_store :cookie_store, key: '_elegato_session'
    
    # Use the database for sessions instead of the cookie-based default,
    # which shouldn't be used to store highly confidential information
    # (create the session table with "rails generate session_migration")
    Myapp::Application.config.session_store :active_record_store
    
  2. rake db:sessions:create

    invoke  active_record
      create    db/migrate/20120729025112_add_sessions_table.rb
    
  3. rake db:migrate

    ==  CreateLinkedinUsers: migrating ============================================
    -- create_table(:linkedin_users)
      -> 0.0236s
    ==  CreateLinkedinUsers: migrated (0.0237s) ===================================
    
    ==  AddSessionsTable: migrating ===============================================
    -- create_table(:sessions)
      -> 0.0012s
    -- add_index(:sessions, :session_id)
      -> 0.0006s
    -- add_index(:sessions, :updated_at)
      -> 0.0006s
    ==  AddSessionsTable: migrated (0.0026s) ======================================
    
  4. To find out what table is actually created, I open the sqlite3 file

    sqlite> .schema sessions
    CREATE TABLE "sessions" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "session_id"   varchar(255) NOT NULL, "data" text, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL);
    CREATE INDEX "index_sessions_on_session_id" ON "sessions" ("session_id");
    CREATE INDEX "index_sessions_on_updated_at" ON "sessions" ("updated_at");
    

So, there is a "data" field in sessions table that will store everything related to the session.

Now, onto my question :-)

I need to store values for 2 variables in session: access_token and request_token. Can I use following? (the way I used to store session values for a cookie)

session[:access_token] = <blah>
session[:request_token] = <some other blah?

And if it does work, does ruby store both variables in the "data" field of the table as an array.

Thanks much for your help!

2 Answers
Related