【发布时间】:2016-11-16 21:31:06
【问题描述】:
我有一个 Angular 2 应用程序,它使用 Rails 5 API 创建项目(想想帖子)。我试图在创建时将 current_user id 添加到新项目(请参阅 Projects 控制器中的尝试),但我得到 NoMethodError(未定义的方法projects' for nil:NilClass): app/controllers/projects_controller.rb:18:increate'。第 18 行是在创建时尝试使用 current_user 的行项目。如果我删除当前用户并使其成为 Project.new 或者如果我在客户端对 user_is 进行硬编码,则没有问题,但有很多用户,这将是一个问题。最后,我想知道如何获取当前用户id并在创建项目时插入。
应用程序控制器
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
【问题讨论】:
标签: ruby-on-rails devise ruby-on-rails-5