[英]How can I resend a Devise confirmation email automatically, but only once, for users who have not confirmed?
I am using Rails with Devise confirmable
. 我使用Rails与设计
confirmable
。 When users sign up Devise automatically sends them a confirmation email. 用户注册后,Devise会自动向他们发送一封确认电子邮件。 If they haven't confirmed after three days, I would like to send them another confirmation email with a new token.
如果三天后仍未确认,我想再给他们发送一封包含新令牌的确认电子邮件。 If they still do not confirm after this second email, we should send them no more.
如果他们在第二封电子邮件后仍未确认,我们将不再发送给他们。 Mapped out on a timeline:
在时间轴上映射:
I'd rather not add a new column to my Users model that keeps track of how many times they've been sent a confirmation email since I think I can do it in a Worker that runs every day using the information we already have. 我不想在用户模型中添加新列来跟踪发送确认电子邮件的次数,因为我认为我可以在每天运行的Worker中使用已有的信息来进行确认。 However I'm struggling a bit with getting the logic right.
但是,我在为正确的逻辑做一些努力。
Here's what I have so far: 这是我到目前为止的内容:
# workers/resend_confirmation_worker.rb
class ResendConfirmationWorker
include Sidekiq::Worker
sidekiq_options queue: :resend_confirmation, retry: false
def perform
users = User.where('confirmation_sent_at IS NOT NULL and
confirmed_at IS NULL')
users.each do |user|
return if user.created_at < Time.zone.now - 4.days || user.created_at > Time.zone.now - 3.days
user.resend_confirmation!
end
end
# config/clock.rb
module Clockwork
every(1.day, 'Resend confirmation') { ResendConfirmationWorker.perform_async }
end
Appreciate any help or suggestions for improvement. 感谢任何帮助或改进建议。
If you are going to run the worker once a day, you could probably use something like: 如果您打算每天运行一次该工作程序,则可能使用类似以下的方法:
User.where('
confirmed_at IS NULL
AND created_at >= ?
AND created_at <= ?
', 2.days.ago.beginning_of_day, 2.days.ago.end_of_day)
If you run this on Wednesday, it fetches all unconfirmed users that are registered on Monday. 如果您在星期三运行此命令,它将获取在星期一注册的所有未确认用户。
d = 2.days.ago
users = User.where.not(confirmation_sent_at: nil)
.where(confirmed_at: nil)
.where(created_at: d.beginning_of_day..d.end_of_day)
users.find_each do |user|
user.resend_confirmation!
end
The answer posted by max is almost perfect however you need to use user.send_confirmation_instructions
instead of resend_confirmation!
max发布的答案几乎是完美的,但是您需要使用
user.send_confirmation_instructions
而不是resend_confirmation!
, and if the worker ran more than once in a day by accident (eg due to a dyno restart), people could potentially get too many confirmation emails. ,并且如果该工人一天偶然地不止一次运行(例如由于dyno重新启动),人们可能会收到太多确认电子邮件。
Now all I'm trying to figure out is why my tests aren't working . 现在我要弄清楚的是为什么我的测试无法正常工作 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.