Search code examples
ruby-on-rails-4pathcontrollerdeviseconsole

In Rails 4, how can I get the path of a controller method from the console?


I’m using devise 4.2 with with Rails 4.2. I have this in my routes.rb file, within a namespace

devise_scope :user do
  post 'sessions' => 'sessions#create'
  delete 'sessions' => 'sessions#destroy'
end

Which I believe should be mapping to this controller

class Auth::SessionsController < Devise::SessionsController
  layout false
  skip_before_action :verify_authenticity_token
end

From the Rails console, I would like to confirm what the path will be for the "create" method of this controller. I tried this

my-app(dev)> url_for controller: :auth_sessions, only_path: true
NoMethodError: undefined method `url_for' for main:Object
    from (irb):4
    from /usr/share/rvm/gems/ruby-2.4.5@my-app/gems/railties-4.2.10/lib/rails/commands/console.rb:110:in `start'
    from /usr/share/rvm/gems/ruby-2.4.5@my-app/gems/railties-4.2.10/lib/rails/commands/console.rb:9:in `start'
    from /usr/share/rvm/gems/ruby-2.4.5@my-app/gems/railties-4.2.10/lib/rails/commands/commands_tasks.rb:68:in `console'
    from /usr/share/rvm/gems/ruby-2.4.5@my-app/gems/railties-4.2.10/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
    from /usr/share/rvm/gems/ruby-2.4.5@my-app/gems/railties-4.2.10/lib/rails/commands.rb:17:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'
my-app(dev)>

But am getting the above error.


Solution

  • You can access the routes in the rails console by using either app or directly Rails.application.routes:

    app.url_for(controller: "auth/sessions", action: :new, only_path: true)
    # => "/auth/users/sign_in"
    
    Rails.application.routes.url_for(controller: "auth/sessions", action: :new, only_path: true)
    # => "/auth/users/sign_in"