Search code examples
ruby-on-railsdevise

add your own custom route to devise


i've seen a bunch of posts on how to rename already-declared routes in devise. I want to expand devise to have my own route check for and idle session. I am implementing a simple js check every 1 minute that I want to hit 'check_active' in the devise sessions controller. I tried this but no luck:

devise_scope :sessions do
    get 'check_active'
end

Is there way to expand devise with a custom route (not rename an already-existing one) ?

UPDATE - almost there, i did this

# already had this in routes

devise_for :users, :controllers =>
    { registrations: 'registrations',
    confirmations: 'confirmations',
    sessions: 'sessions',
    passwords: 'passwords',
    omniauth_callbacks: "omniauth_callbacks"}

# added this

devise_scope :sessions do
    get '/check_active' => 'sessions#check_active'
end

I have a js firing, i have it get '/check_active' as rake routes shows this:

check_active GET      /check_active(.:format)

But when it fires, the controller 404s with

AbstractController::ActionNotFound (Could not find devise mapping for path "/check_active".
This may happen for two reasons:

1) You forgot to wrap your route inside the scope block. For example:                                                                                        

  devise_scope :user do                                                                                                                                      
    get "/some/route" => "some_devise_controller"                                                                                                            
  end                                                                                                                                                        

2) You are testing a Devise controller bypassing the router.                                                                                                 
   If so, you can explicitly tell Devise which mapping to use:                                                                                               

   @request.env["devise.mapping"] = Devise.mappings[:user]

):

Solution

  • If you are overwriting Devise's default controllers, it is not any different from any other controller to add your own route.

    After you create your devise controllers to overwrite, do the following:

    Under sessions_controller declare a method

    # app/controllers/devise/sessions_controller.rb
    def check_active
       # do what you want to do
    end
    

    And in your router:

    # config/routes.rb
    devise_scope :sessions do
        get 'check_active', to: "devise/sessions#check_active"
    end