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