2016-11-16 9 views
0

Rails 5 APIを使用してプロジェクト(投稿を考える)を作成するAngular 2アプリがあります。私は、プロジェクトを作成するときにcurrent_userを使用しようとする行です。現在のユーザーを削除してProject.newにするか、クライアント側でuser_isをハードコードしても問題はありませんが、多くのユーザーにとってはこれが問題になります。現在のユーザーIDとプロジェクトを作成するときにそれを挿入します。Devailsで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

解決済み。問題は、angle2トークンが、私のプロジェクトルートなどの非認証ルートへのその後のリクエストに対して正しいヘッダーを渡していないことでした。 current_userは今すぐ行けます。

+0

私は同様の問題を抱えていますが、angular2トークンを使って正しいヘッダをどのように追加しましたか? –

1

current_userを設定するauthenticate_user!メソッドを呼び出していないようです。

おそらく、このようなあなたのApplicationControllerルック何かを作ってみる...ここ

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

    before_action :authenticate_user! 
end 

before_action呼び出しがcurrent_userメソッドが値を返すことを保証します。

+0

マークをヒットしません。 Simpleは以下のように401をスローします:DeviseTokenAuth :: SessionsController#JSONとしての処理 パラメータ:{"email" => "[email protected]"、 "password" => "[FILTERED]"、 "session" => [Active_model_serializers]レンダリングされたActiveModel :: Serializer :: Null with Hash(0.19ms) フィルタチェーンが次のように停止しました:{"email" => "[email protected]"、 "password" => "[FILTERED] authenticate_user!レンダリングまたはリダイレクトされました 5ミリ秒で不正な401(ビュー:3.8ms | ActiveRecord:0.0ms) – Joel

関連する問題