Rails Tutorial — 9.3.3 Current_User

后端 未结 1 917
故里飘歌
故里飘歌 2020-12-18 16:16

So I\'m following the Rails Tutorial, and I\'ve gotten to the portion where we want to sign a user in with a sign_in SessionHelper.

Question 1:

相关标签:
1条回答
  • 2020-12-18 17:12

    Remember that instance variables like @current_user are only set for the duration of the request. The controller and view handler instances are created specifically for rendering once and once only.

    It is often easy to presume that because you've set a variable somewhere that it will continue to work at some point in the future, but this is not the case. To preserve something between requests you need to store it somewhere, and the most convenient place is the session facility.

    What's missing in this example is something along the lines of:

    def current_user
      @current_user ||= User.find_by_remember_token(cookies[:remember_token])
    end
    

    Generally it's a good idea to use the write accessor to map out the functionality of the sign_in method you've given as an example:

    def current_user=(user)
      cookies.permanent.signed[:remember_token] = [user.id, user.salt]
      @current_user = user
    end
    

    It's odd that there is a specific "sign in" method when the act of assigning the current user should be the same thing by implication.

    From a matter of style, though, it might be more meaningful to call these methods session_user as opposed to current_user for those situations when one user is viewing another. "Current" can mean "user I am currently viewing" or "user I am currently logged in as" depending on your perspective, which causes confusion. "Session" is more specific.

    Update:

    In response to your addendum, the reason for using cookies to read and cookies.permanent to assign is much the same as using flash.now to assign, and flash to read. The .permanent and .now parts are intended to be used when exercising the assignment operator.

    0 讨论(0)
提交回复
热议问题