繁体   English   中英

如何使用devise_token_auth在Rails中获取current_user?

[英]How to get current_user in Rails using devise_token_auth?

我用devise_token_auth设计一种身份验证和登记。 一切顺利:我可以登录,使用api和web界面注销。 但是我无法获得current_user设计变量(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

我需要将此变量用作全局,例如,在application.html.erb中使用

尝试这个

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

  def index
    @user = current_user
  end
end

注意before_action
authenticate_user! 负责设置current_user

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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