views:

240

answers:

2
  • WARNING: Complete newbie to RoR and Ruby alert! *

I have a login method that looks like this:

@user = Person.find(:first, :conditions => ["email=?", params[:email]])
if @user and @user.password==params[:user_password]
   session[:user] = @user
else
   flash[:warn] = 'Invalid password!'

However, the user record can get very large, so I don't want to store the entire user record in my cookie session.

How can I modify this code so that a specific field does not get stored in the session? There are two fields that can get very large (very large user profile data) and will not fit within the cookie session 4 kilobyte limit, so I want to exclude those from being stored in the session.

+2  A: 

I would do :

session[:user] = @user.id

And then create a before_filter going something like this:

before_filter :get_user

def get_user
  @user = User.find_by_id(session[:user])
end

edit: This is not exactly what you were looking for, but if you can't store all the object in the session variable you might want to consider this option. It's only one request so it won't be too resource intensive. Plus like this you can check at every page load that the user exists and this might be helpful, security wise.

marcgg
Storing the entire model in the session is also a bad idea if you ever change the model and update the application. Instances in older sessions may not work well with the new model class.
Steve Madsen
+1 to this, I agree that this is something to avoid
marcgg
Thanks, this worked. I inherited the application from someone else... I didn't even know any Ruby up until about 30 minutes ago. :-)
Keith Palmer
Aha, well I'm glad it helped! Good luck maintaining this. It looks like sloppy code (based on the fact that he put a model in a session variable), hopefully you'll get around. If you want to learn rails, get Agile Web Dev with Rails (the latest version)... it's really good :)
marcgg
I thought you didn't have the time or resources to rebuild the application so that it only stores the user ID?
John Topley
I didn't, I'm not late on another project. Woohoo, looks like it'll be a late night tonight. :-) The code looks *very* sloppy to me, even though I know only a little Ruby. There's a lot of nasty looking cruft, and absolutely 0 comments or documentation. Yuck!
Keith Palmer
A: 

The design of Rails often serves to steer you in a very specific direction. In this case, the fact that by default Rails' sessions are stored in a cookie is a strong hint that you shouldn't be storing large objects in the session. By all means store the User ID, but not the User object itself.

John Topley
Unfortunately, I didn't build the application, I'm just trying to get it to work. I don't have the time or resources to re-build the application so that it only stores the User ID.
Keith Palmer