Hisham Malik Hisham Malik - 2 months ago 9
Ruby Question

NoMethodError in DocsController#new undefined method `docs' for nil:NilClass

I am trying to follow a tutorial and build an app like evernote or google docs where a user can store files. I am trying to associate users with the docs and I want the current user to create a new doc and I want that doc to have the id of that user and I get this error when trying to create a new
NoMethodError in DocsController#new
undefined method `docs' for nil:NilClass

Extracted source (around line #13):
11
12
13
14
15
16

def new
@doc = current_user.docs.build
end

def create


Rails.root: /Users/Hisham/Desktop/Rails_projects/cabinet

Application Trace | Framework Trace | Full Trace
app/controllers/docs_controller.rb:13:in `new'

Answer

Probably you got this error because you are not logged, and current_user equals nil. You should check that user is logged before this action and create something callback. Devise offers you:

before_action :authenticate_user!   

and you shoud use it in your controller like this:

before_action :authenticate_user!, only: [:new,:create]