0

I am currently following a recipe box tutorial on youtube. When I open the rails console and type

@recipe = current_user.recipes.build

I got the following error:

NameError: undefined local variable or method `current_user' for main:Object
from (irb):3
from /Users/matthiascordes/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/commands/console.rb:65:in `start'
from /Users/matthiascordes/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/commands/console_helper.rb:9:in `start'
from /Users/matthiascordes/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:78:in `console'
from /Users/matthiascordes/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:49:in `run_command!'
from /Users/matthiascordes/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/commands.rb:18:in `<top (required)>'
from bin/rails:9:in `require'
from bin/rails:9:in `<main>'

Does anybody has an idea what is wrong and how I can solve this problem? I am using the devise gem for my user model.

3 Answers 3

3

you can not access current_user inside your rails console,so try

user = User.find(your_user_id)
user.recipes.build
Sign up to request clarification or add additional context in comments.

2 Comments

All right, I will try that. Where exactly do I have to add these lines?
inside your rails console, because you're trying to access current_user inside console, for that you need a user to perform some operations, so for example you can do, user = User.find(id), now you have a user to perform something
1

current_user is a variable provided by one of the before_filters of devise, therefore, outside a controller you don't have access to it, if you still want to be in that context, you can use gem byebug and drop a byebug inside your code, or a debugger and the execution will stop and you will be in the scope you need, to test all you are required, otherwise, plain in rails c, you will need to fetch the user the old way, with a query

User.find(user_id)

Comments

0

You cannot access current_user in rails console . If you want the user variable, then search it like

user = User.find(some_id)

& then use it like user.recipes.build you can also create the user from rails console like user = User.create(user parameters) & then use it building receipies

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.