Reputation: 97
I have an Angular 2 app that is using a Rails 5 API to create projects (think posts). I'm trying to add the current_user id to a new project (see the attempt in the Projects controller) when created but I get NoMethodError (undefined method projects' for nil:NilClass): app/controllers/projects_controller.rb:18:in
create'. Line 18 is the line that attempts to use current_user when creating the project. If I remove current user and make it Project.new or if I hard code the user_is on the client side, there are no issues but with many users, this would be a problem. In the end, I want to know how to get the current user id and insert it when creating the project.
Application Controller
class ApplicationController < ActionController::API
include DeviseTokenAuth::Concerns::SetUserByToken
def current_user
@current_user
end
end
Projects Controller
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
Upvotes: 1
Views: 5796
Reputation: 97
Resolved. Issue was than angular2-token wasn't passing correct headers for subsequent requests to non-auth routes such as my projects routes. current_user is good to go now.
Upvotes: 0
Reputation: 219
Looks like you haven't called the authenticate_user!
method that sets the current_user
.
Perhaps try making your ApplicationController
look something like this...
class ApplicationController < ActionController::API
include DeviseTokenAuth::Concerns::SetUserByToken
before_action :authenticate_user!
end
The before_action
call here ensures that the current_user
method returns a value.
Upvotes: 2