2016-11-16 36 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

相关问题