DaudiHell
DaudiHell

Reputation: 808

NoMethodError in ActiveAdmin::Devise::Sessions#new when logging in as Admin

I'm using ActvieAdmin for the backend of my app.

I did following changes to let my users use their username to sign up to their account.

in config/initializers/devise.rb I changed config.authentication_keys = [:username]

then I added the following lines to the user.rb model

validates :email,uniqueness: true 
validates :username,uniqueness: true

Then I created a migration rails generate migration add_username_to_users username:string:uniq and then rake db:migrate

then in the end I modified the devise views to show :username

I can now log in as a user with username

But I can't log in to ActiveAdmin anymore. I get this error messages

NoMethodError in ActiveAdmin::Devise::Sessions#new

Showing /Users/dadi/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activeadmin-1.2.1/app/views/active_admin/devise/sessions/new.html.erb where line #8 raised:

undefined method `username' for #<AdminUser id: nil, email: "", created_at: nil, updated_at: nil>

I'm not sure How I can make ActiveAdmin log_in work again. Can anyone help me with this?

Upvotes: 0

Views: 1141

Answers (1)

Wasif Hossain
Wasif Hossain

Reputation: 3960

Assuming that you are using multiple models with Devise (AdminUser and User), if you change the authentication_keys in devise initializer config, it will impose the rule for both the models. As username attribute is clearly missing from AdminUser, this method won't work for you.

If you want to authenticate admin_users with email and users with username, then you need to add authentication_keys along with other devise options in the respective models instead of the initializer like so:

# AdminUser
class AdminUser < ApplicationRecord
  ...
  devise :database_authenticatable,..., authentication_keys: [:email]
  ...
end

# User
class User < ApplicationRecord
  ...
  devise :database_authenticatable,..., authentication_keys: [:username]
  ...
end

You may follow this link if you want to allow any of email/username for both type of users

Upvotes: 1

Related Questions