Tuesday, July 03, 2007

Making Rails' session work with Facebook

When using Facebook and ActiveRecordStore for sessions in Rails, rails generates a new session for every request. The following is a quick solution to the problem. First change your application's session_key by adding the following to the bottom of environment.rb.
ActionController::Base.session_options['session_key'] = 'fb_sig_session_key'

Next, override ActiveRecordStore#initialize to by adding the following to the bottom of environment.rb

class CGI
class Session
class ActiveRecordStore
def initialize(session, option = nil)
session_id = session.session_id
unless @session = ActiveRecord::Base.silence { @@session_class.find_by_session_id(session_id) }
@session = @@session_class.new(:session_id => session_id, :data => {})
end
end
end
end
end

Then restart your server. Your session should now persist between requests and have the same id as fb_sig_session_key.

5 comments:

notmyrealname said...

Thanks!

I was starting to get pretty frustrated and ended up questioning age old methods or accessing the session :) Found what the problem was just before I found your solution!

Unknown said...

If I apply your fix the session problem with in facebook applications will rails try to use the "fb_sig_session_key" arguement from requests that come from a normal browser instead of facebook? How can I apply this solution so non facebook parts of my rails application will not be affected?

Unknown said...

Another question :). How will the created using this solution expire?

Arndt Jenssen said...

Should it be:

ActionController::Base.session_options['session_key'] = 'xxx'

Arndt Jenssen said...

Sorry - it should be:

ActionController::Base.session_options['session_id'] = 'xxx', that is using 'session_id' instead of 'session_key'