2016-11-16 33 views
0

我有一個使用Rails 5 API創建項目(思考帖子)的Angular 2應用程序。我試圖在創建時將current_user id添加到新項目(請參閱Projects控制器中的嘗試),但是我得到NoM​​ethodError(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 
+0

http://zacstewart.com/2015/05/14/using-json-web-tokens-to-authenticate-javascript-front-ends-on-rails.html – 7urkm3n

回答

0

已解決。問題比angular2-token沒有傳遞正確的頭文件給隨後的請求到非auth路由,比如我的項目路由。 current_user現在很好。

+0

我有類似的問題,您是如何使用angular2-token添加正確的頭文件的? –

1

看起來你還沒有調用authenticate_user!方法設置current_user

也許嘗試讓你的ApplicationController是這個樣子......

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

    before_action :authenticate_user! 
end 

before_action來電來訪確保current_user方法返回一個值。

+0

不打標記。簡單的拋出401如下:處理DeviseTokenAuth :: SessionsController#創建爲JSON 參數:{「email」=>「[email protected]」,「password」=>「[FILTERED]」,「session」=> {「email」=>「[email protected]」,「password」=>「[FILTERED]」}} [active_model_serializers]呈現ActiveModel :: Serializer :: Null with Hash(0.19ms) 過濾器鏈暫停爲:的authenticate_user!呈現或重定向 已完成401 5毫秒內未經授權(查看:3.8ms | ActiveRecord:0.0ms) – Joel

相關問題