使用devise-auth-token改用手机号登录后,无法禁用邮箱验证
解决Devise Token Auth移除邮箱验证规则的问题
看起来你已经成功切换到用手机号登录,但被Devise Token Auth默认的邮箱验证规则卡住了对吧?别担心,这是因为Devise Token Auth的User concern自带了邮箱相关的验证,再加上confirmable模块也会依赖邮箱字段,我们一步步来解决:
1. 移除或调整confirmable模块(关键)
你的代码里加了:confirmable,这个模块默认会强制要求邮箱字段存在,因为它需要发送确认邮件。如果你不需要邮箱确认功能,直接把它从devise配置里删掉:
class User < ActiveRecord::Base include DeviseTokenAuth::Concerns::User # 去掉:confirmable,若必须保留可看后续扩展步骤 devise :database_authenticatable, authentication_keys: [:phone_number] mount_uploader :avatar, AvatarUploader # 你的其他验证规则 validates :first_name, presence: true, format: {with: /[[:word:]]/} validates :last_name, presence: true, format: {with: /[[:word:]]/} # 覆盖Devise Token Auth默认的邮箱验证 validates :email, allow_nil: true, allow_blank: true, uniqueness: false end
2. 覆盖Devise Token Auth的默认邮箱验证
DeviseTokenAuth::Concerns::User里默认给email加了presence: true和uniqueness: true的验证,我们需要在User模型里重新定义这个验证,允许邮箱为空且不要求唯一。上面的代码已经加了这一行,记得要放在include那个concern之后,这样才能覆盖默认规则。
3. 数据库字段调整
确保你的users表中email字段允许为空。如果之前的迁移里设置了null: false,需要生成一个迁移来修改:
rails generate migration ChangeEmailNullInUsers
然后编辑迁移文件:
class ChangeEmailNullInUsers < ActiveRecord::Migration[6.1] def change change_column_null :users, :email, true end end
运行迁移:rails db:migrate
4. 调整Devise Token Auth初始化配置(可选)
如果你完全不需要邮箱相关的功能,打开config/initializers/devise_token_auth.rb,做以下调整:
# 重置密码用手机号而不是邮箱 config.reset_password_keys = [:phone_number] # 关闭自动发送确认邮件(若之前保留了confirmable) config.send_confirmation_email = false
扩展:若必须保留confirmable模块
如果你的业务需要确认功能,但想用手机号而非邮箱,那需要重写confirmable的逻辑:
- 重写
send_confirmation_instructions方法,发送短信验证码替代邮件 - 在模型里添加手机号的验证规则,确保其唯一性和合法性
- 自定义确认控制器,处理手机号验证码的验证流程
不过这部分会复杂很多,如果你只是想移除邮箱验证,优先考虑前面的基础步骤。
内容的提问来源于stack exchange,提问作者Ali Abdelrahman
相关产品推荐
相关产品推荐

