可能是因为部署的代码中没有正确配置邮件服务器,导致无法发送激活邮件。可以在生产环境的配置文件(如config/production.rb)中加入以下代码:
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
domain: 'example.com',
user_name: '',
password: '',
authentication: 'plain',
enable_starttls_auto: true
}
其中, 和 分别是邮件服务器的用户名和密码,可以在邮件服务器的管理界面中获取。这里以 Gmail 邮件服务器为例进行说明,如果使用其他邮件服务器,则需要根据具体情况修改配置参数。
另外,还需要在项目中启用用户激活功能。可以通过以下步骤实现:
在用户模型(如app/models/user.rb)中添加以下代码:
class User < ApplicationRecord
# ...
before_create { generate_token(:auth_token) }
# ...
def generate_token(column)
begin
self[column] = SecureRandom.urlsafe_base64
end while User.exists?(column => self[column])
end
end
这段代码会在用户创建时自动生成一个 auth_token,用于激活链接的访问凭证。
在用户控制器(如app/controllers/users_controller.rb)中添加以下代码:
class UsersController < ApplicationController
# ...
def create
@user = User.new(user_params)
if @user.save
# 发送激活邮件
UserMailer.account_activation(@user).deliver_now
flash[:info] = "请检查你的邮箱并激活账号。"
redirect_to root_url
else
render 'new'
end
end