我有一個使用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