Alex Ermolaev
Alex Ermolaev

Reputation: 311

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

Upvotes: 1

Views: 3256

Answers (1)

Mihai Dinculescu
Mihai Dinculescu

Reputation: 20033

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.

Upvotes: 0

Related Questions