ruby-on-railssessionactiverecordsession-store

How to persist the session in Rails before the end of request?


I'm using Rails 2.3 and ActiveRecord as session store and I want to avoid creating sessions before it is needed.

I have a Itens table to store items associated to the session, ie, its model has an association belongs_to :session.

I have an Ajax call that should create a new item. When there is no session yet, it should create one to be associated to the item. For this, I need the id from sessions table, not the session_id used for identify the sesssion by the cookie. But, the session record is only created in DB after the request has finished. Ex:

def create
  request.session_options[:id] # nil if there is no session yet
  session[:activate] = 1 # this "creates" the sesssion (but not in DB)
  request.session_options[:id] # now the new generated session_id
  db_session = Session.find_by_session_id(request.session_options[:id]) # nil, not in DB yet :(
  Item.new(
    :session_id => db_session.id, # ops, id called for nil object
    :data => params[:data]
  )
end

Solution

  • "Model objects should not know anything about the session" (Pat Maddox from http://markmail.org/message/4ilmpn7s3wkq6iod).

    And this make sense, since if I decided to store session in memory, cookie, file system or wherever, nothing is changed in the model code.

    So, the solution is to create another table to store items_groups. If there is no session yet, create a new items_group and store its id on the session. Otherwise, retrieve items_group_id from session and we're done!

    When the session is stored in database doesn't matter anymore.