Devise: Replace 'email' with alternative f

2019-08-14 04:32发布

问题:

I tried to replace email with accountnumber throughout my whole application using Sublime's "replace in all files" feature.

I've reset and re-migrated the DB, however, when registering I still get the following error:

undefined method `email' for #<Account:0x415b690>

and then the following parameters

    {"utf8"=>"✓",
 "authenticity_token"=>"2qqA7dx99hx+VqkZGDmySNJd+2Fzxuanegy1ysrpD30=",
 "account"=>{"accountnumber"=>"1307",
 "password"=>"[FILTERED]",
 "password_confirmation"=>"[FILTERED]"},
 "commit"=>"Sign up"}

Has anyone had this difficulty before?

回答1:

With Devise, the convention is to use 'email' for sign in. You're using a gem (Devise), so not all the code is visible in your project, and a search-and-replace to substitute 'accountnumber' for 'email' is not enough. You have to reconfigure Devise by making changes to your Account model.

Be sure to change 'email' to 'accountnumber' in the migration Devise created ('DeviseCreateUsers') and run rake db:migrate:reset.

Change your Account model:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,  
         :authentication_keys => [:accountnumber]

  def email_required?
    false
  end

  def email_changed?
    false
  end

end

Make sure you've generated Devise views and changed 'email' to 'accountnumber' in the view files.

I've written a Rails Devise Tutorial that will help you understand how Devise works.