Dodinas
Dodinas

Reputation: 6805

Storing User Data in Session - Standard Practice

I've seen some information on SO and Google regarding storing user data for sessions, but most have been for PHP and not Rails.

Additionally, I've watched Dangers of Model in Session on RailsCasts.

Let's say I have a user that logs in, and I want to access some basic preferences from the user like: zip code, height, weight, and perhaps, 10 other things that I would like to access later.

Should I?

  1. Store those 10 things in a hashed session variable?

    e.g., session[:user_prefs] = User.find(:first)

  2. Just store the user's ID as a sesion variable, and then run queries later to access the zip code, height, weight, etc?

    e.g., session[:user_id] = User.find(:first).id

  3. Or, is there something entirely different that I should be doing?

I'm not sure what the standard coding practice or best practice would be for this scenario.

Any help would be great.

Upvotes: 1

Views: 361

Answers (1)

vee
vee

Reputation: 38645

Option 2 is the way to go.

Option 1 is "No" because your session data will be out of sync with the database as soon as the user information gets updated. Say for example you store those ten fields in the session upon user login, and later in the application the user updates one of those ten fields, now the session data is out of sync with the database. You could define a function that updates the session data when one of the attributes changes but I think this adds unnecessary extra complexity to the application.

Option 3, I cannot think of anything that replaces the session for this requirement. There are other ways you could implement the session logic but they would just be your version of already provided(by Rails) implementation of session.

Upvotes: 1

Related Questions