views:

35

answers:

2

I have a standard query that gets the current user object:

@user = User.find_by_email(session[:email])

but I'm putting it as the first line in every single controller action which is obviously not the best way to do this. What is the best way to refactor this?

Do I put this as a method in the Application controller (and if so, can you just show me a quick example)?

Do I put the entire @user object into the session (has about 50 columns and some sensitive ones like is_admin)?

Or is there another way to remove this kind of redundancy?

A: 

You could specify a before_filter, which is automatically called at the beginning of every controller action. Read up on it to see how to use it.

Jason Miesionczek
+2  A: 

I suggest making it into a helper placed in the ApplicationHelper module

def current_user
  return nil if @user === false
  #This ensures that the find method is only called once
  @user = @user || User.find_by_email(session[:email]) || false
end

I prefer the above usage instead of the standard @user ||= User.find... because it prevents repetitive queries if the user record isn't found the first time. You could also just bang the find method: find_by_email! to make it throw an exception when the user can't be found

Daniel Beardsley
I'll still be able to use attributes right? like current_user.first_name, or accessors in the model like current_user.firstlast?
Kevin
Yes, `current_user` just returns the `@user` (methods in ruby return the value of the last line executed in a method) variable which is set to an instance of the `User` model
Daniel Beardsley