简体   繁体   中英

devise - can't display sign in or sign out in rails view

I'm using devise to do basic authentication for now. When I go to localhost:3000/users/sign_in I will be able to sign in or if I go there when I'm logged in I'll get the appropriate message "You are already signed in."

However, user_signed_in? is always evaluating to false, even after successful sign in

<div id="user_nav">
    <% if user_signed_in? %>
      Welcome <%= current_user.email %>!
      <%= link_to "Sign out", destroy_user_session_path, :method => :delete %>
    <% else %>
      <%= link_to "Connect With Facebook", "/auth/facebook" %>
      <%= link_to "Sign out", destroy_user_session_path, :method => :delete %>
    <% end %>
  </div>
  <% flash.each do |name, msg| %>
    <%= content_tag :div, msg, :id => "flash_#{name}" %>
  <% end %>
</div>

Here is config/application.rb

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_filter :authenticate_user!
  private
  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end
  helper_method :current_user
end

How can I get user_signed_in? to be true? current_user also continues to be false, whether I successfully sign in or not

This is probably because you are defining your own current_user method. This will then override the one that is provided by Devise.

If you look the source for the user_signed_in? method , you can see that current user (the one defined by Devise) is used by this method. It is likely that Devise doesn't save the current user to session[:user_id], which is what your method is checking. Consequently, when Devise calls your method from within user_signed_in?, it always returns false.

Try removing the current user method from your ApplicationController and see if that resolves the problem.

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