简体   繁体   中英

How to get current_user in Rails using devise_token_auth?

I use devise_token_auth with devise for auth and registration. Everything goes well: I can sign in, sign out using api and web interface. But I can't get current_user devise variable (nil).

<% if current_user %>
    <%= link_to "Edit profile", edit_user_registration_path(current_user.id) %> |
    <%= link_to('Logout', destroy_user_session_path, :method => :delete) %>
  <% else %>
    <%= link_to "Register", new_user_registration_path %> |
    <%= link_to('Login', new_user_session_path) %>
  <% end %> 

application_controller.rb

class ApplicationController < ActionController::Base
  include DeviseTokenAuth::Concerns::SetUserByToken
  protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }
end

I need this variable as a global for using, for example, in application.html.erb

Try this

# app/controllers/test_controller.rb
class TestController < ApplicationController
  before_action :authenticate_user!

  def index
    @user = current_user
  end
end

Notice the before_action .
authenticate_user! is responsible for setting current_user .

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