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.