简体   繁体   中英

Ruby on Rails - Logging users in and out

I've designed the following Helper class to work with logging in and logging out users based primarily on information I've found in tutorials online, though I've run into an error.

module SessionHelper

    def login(user)
        session[:user] = user.id
    end

    def current_user
        @current_user ||= User.find_by( session[:user] )
    end

    def logged_in?
        !current_user.nil?
    end

    def logout
        session.delete(:user)
        @current_user = nil
    end

end

When I call the "logout" method, the @current_user session variable does not get destroyed. In one view, I have the following code written.

<% if logged_in? %>
    <div class="login">
        Welcome back, <a href="#">@<%= @current_user %></a>!
    </div>
<% end %>

Even though my user gets logged out, the still is displayed and the @current_user is displayed as "#".

I'm just curious if anyone may be able to offer any assistance on this for me. If so, thank you very much!

Why don't you try to use link_to helper instead of href ? Another thing that feels not so right is your call to logout helper method. Since it is not obvious how you are calling it, I would suggest to use method: :delete , which means that the get request is made delete request by javascript in Ruby on Rails.

So, if I was in your shoes, it would be:

Welcome back 
<%= link_to current_user, "#" %>

No <a href> and </a> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM