如何使用 Devise 在 Rails 5 API 中获得 current_user

How to get current_user in Rails 5 API with Devise

我有一个 Angular 2 应用程序正在使用 Rails 5 API 创建项目(想想帖子)。我试图在创建时将 current_user id 添加到新项目(请参阅项目控制器中的尝试),但我得到 NoMethodError(未定义的方法 projects' for nil:NilClass): app/controllers/projects_controller.rb:18:increate'。第 18 行是尝试的行在创建项目时使用current_user。如果我删除当前用户并将其设为Project.new,或者如果我在客户端硬编码user_is,则没有问题,但有很多用户,这会是个问题。最后想知道如何获取当前用户id并在创建项目时插入。

应用程序控制器

class ApplicationController < ActionController::API
  include DeviseTokenAuth::Concerns::SetUserByToken

  def current_user
    @current_user
  end

end

项目总监

def create
  @project = current_user.projects.new(project_params)

  if @project.save
    render :show, status: :created, location: @project
  else
    render json: @project.errors, status: :unprocessable_entity
  end
end

您似乎还没有调用设置 current_userauthenticate_user! 方法。

也许试着让你的 ApplicationController 看起来像这样...

class ApplicationController < ActionController::API
  include DeviseTokenAuth::Concerns::SetUserByToken

  before_action :authenticate_user!
end 

此处的before_action调用确保current_user方法returns一个值。

已解决。问题是 angular2-token 没有为后续请求传递正确的 headers 到 non-auth 路由,例如我的项目路由。 current_user 现在可以开始了。