我有一个使用Rails 5 API创建项目(思考帖子)的Angular 2应用程序。我试图在创建时将current_user id添加到新项目(请参阅Projects控制器中的尝试),但是我得到NoMethodError(undefined方法projects' for nil:NilClass): app/controllers/projects_controller.rb:18:in
create'。第18行是尝试在创建项目时使用current_user的行。如果我删除当前用户并使其成为Project.new,或者如果我在客户端硬编码user_is,则没有问题,但对于许多用户,这将是一个问题。最后,我想知道如何获取创建项目时,当前的用户ID和插入。如何使用Devise获取Rails 5 API中的current_user
应用控制器
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
http://zacstewart.com/2015/05/14/using-json-web-tokens-to-authenticate-javascript-front-ends-on-rails.html – 7urkm3n