开发者

Where do I put the Current user query so as to not repeat per controller?

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 (开发者_Python百科has about 50 columns and some sensitive ones like is_admin)?

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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜