Storing model object in session in EdgeRails


#1

I’m having a problem with sessions since upgrading to EdgeRails. Against
certain recomendations, I’m storing the current user’s model object in
the session. This worked fine in 1.0 and earlier, but now I am noticing
that any time I reference the associated objects for an object stored in
the session, the associated objects get copied into the session! For
example, session[:user].posts will copy all of the users’s posts into
the session. If i delete a post from the database, the session still
returns the deleted post unless I reload the session[:user] object.

Is there anything I can do to restore the old session behavior? I don’t
really want to rewrite my app to store the current user in a different
way. My User model references some of user properties that are only
stored in the session. It would be a non-trivial task to change this.
Also, I don’t want to have to worry about reloading the user every time
I change the database.

-matthew


#2

Update:

I found a workaround. Anytime I want to use session[:user], I make a
“deep clone” of the object and work with that unless I am actually
updating the user object (rare). In which case I work with session
directly and reload it as necessary.

So in my User model:

def deep_clone
Marshal::load(Marshal.dump(self))
end

And in a controller before_filter:

@user = session[:user].deep_clone

I couldn’t use just clone() because made a new record.

-matthew


#3

Hello Matthew,

2006/3/13, Matthew I. removed_email_address@domain.invalid:

I found a workaround. Anytime I want to use session[:user], I make a
“deep clone” of the object and work with that unless I am actually
updating the user object (rare). In which case I work with session
directly and reload it as necessary.

I have another solution, if you want to take a look at it:

http://blog.teksol.info/articles/2005/10/21/model-serialization-in-session

Bye !


#4

2006/3/13, Matthew I. removed_email_address@domain.invalid:

Unfortunately I can’t use this because I store more than just database
properties in the user model. Each user has group membership
information which comes from LDAP (after authentication).

Change _dump to suit:

def _dump(ignored)
stream = []
stream << self.id
stream << self.ldap_params
stream.inspect
end

def self._load(stream)
params = eval(stream)
model = find(params[0])
model.ldap_params = params[1]
model
end

Untested code, but should work.

Bye !


#5

François Beausoleil wrote:

I have another solution, if you want to take a look at it:

http://blog.teksol.info/articles/2005/10/21/model-serialization-in-session

Very clever!

Unfortunately I can’t use this because I store more than just database
properties in the user model. Each user has group membership
information which comes from LDAP (after authentication).

-matthew