accessing current_user in rails console

Viewed 3236

I need to access the current_user attribute in rails console, I have the pry gem installed, but I do not know how to use it to sign in a user

I also tried

user = User.find(1)
sign_in user

in my code to manually log a user in, but this returns the error

Module::DelegationError: ActionController::Metal#session delegated to @_request.session, but @_request is nil: #<ResumesController:0x0055be48209b10 @_action_has_layout=true, @_routes=nil, @_request=nil, @_response=nil>
3 Answers

The whole concept of a "current user" is not applicable when using the console.

The console unlike when you run a rails server is not actually responding to http requests. It just boots up the key railties of the framework so that you can play around with it.

Since there is no HTTP request, there is no session or token based auth. Thus there is no user actually interacting with the system which renders the whole concept moot.

Pry

The pry gem is an alternative console to the default ruby irb.

It can be used to set "interactive breakpoints" in the code so you can halt the execution in the server and inspect variables.

So lets say you have:

class PagesController
  # GET /
  def home
    binding.pry
  end
end

When you request http://localhost:3000/ with your browser the page will not load.

If you switch back to console where you are running the rails server you will notice that there is an interactive prompt. Once you close the prompt (with exit or ctrl + d) the response will be sent to the browser.

The byebug gem is similar but creates an interactive terminal in a standard rails error page.

when you say "rails console", do you mean running it standalone with "rails console" or do you mean the console shown when you use binding.pry in your code and excecution stops and lets you interact with the current request?

you can't set a current_user from a standalone console like @max said because it's a concept related to requests and sessions

you should be able to log in a user if you are talking about the console that stops the current request excecution usingin binding.pry, I'm guessing you are using devise and that code to sign_in would be ok, only that you are mixing the two contexts

as long as you do not need session behavior, just a "current user" e.g. like this

def load_something_for( user = User.current ) . . .

this should work:

[4] pry(main)> User.current = (User.find_by login: :mr_x )
[5] pry(main)> load_something_for() # for Mr.X
Related