Ali Ahmed
Ali Ahmed

Reputation: 108

While creating current_user helper_method in application controller, Why we do not save entire User object in sessions?

I understand how we can simply implement current_user method in application controller. Normally we do

helper_method :current_user
def current_user
  @current_user ||= User.find_by_id(session[:user_id]) if session[:user_id].present?
end

But I noticed that it makes a hit to DB at every request if we have session[:user_id]. So instead of saving user.id in session[:user_id] why we do not save the entire user object in session[:user] and do like this.

def current_user
  session[:user]
end

What stumbling block is here in this approach? At least that will not hit DB on every request and keeps user data in session.

Upvotes: 1

Views: 51

Answers (2)

Ankit Pandey
Ankit Pandey

Reputation: 460

Session store as cookie in user's browser and cookies imply a strict size limit of 4kB. This is fine as you should not store large amounts of data in a session anyway, Storing the current user's database id in a session is usually ok but storing a user's object is not recommended.

Upvotes: 0

Rokibul Hasan
Rokibul Hasan

Reputation: 4156

This is not a good idea to save an object to session. You have to consider few things while store data into session, like

  • How large the data is.
  • Object can change anytime, if you store object into session, that session user will not affect changes.

Upvotes: 1

Related Questions