Search code examples
ruby-on-railsdevisedevise-recoverable

Resetting user password when devise_for routes are in scope


In my application all routes are scoped to a locale, that user has selected like this:

scope ":locale", locale: /#{SpreeI18n::Config.supported_locales.join('|')}/ do
  devise_for :users, skip: :omniauth_callbacks
  get '/', to: 'homepage#index', :as => :homepage
end

When I want to send reset password instructions like User.find(1).send_reset_password_instructions, there is a problem:

Devise::Mailer#reset_password_instructions: processed outbound mail in 4249.9ms
ActionView::Template::Error: No route matches {:action=>"edit", :controller=>"devise/passwords", :reset_password_token=>"-zyuNkscVkwFn2awdm27"} missing required keys: [:locale]

How can I pass locale so that I can send the reset token?


Solution

  • Let's create a custom controller for password:

    1. Customize routes.rb

      scope ":locale", locale: /#{SpreeI18n::Config.supported_locales.join('|')}/ do
        devise_for :users, skip: :omniauth_callbacks, controllers: { passwords: 'my_passwords' }
        get '/', to: 'homepage#index', :as => :homepage
      end
      
    2. my_passwords_controller.rb

      class MyPasswordsController < Devise::PasswordsController
        def create
          resource_params.merge!(locale: 'en') # use 'en' for eg
          super
        end
      end
      

    Then send_reset_password_instructions function will take your customized resource_params when sending the email.

    Please refer to devise sourcecode to understand what devise does in detail!