【问题标题】:Using timestamps in rails to send emails在 Rails 中使用时间戳发送电子邮件
【发布时间】:2011-12-21 13:40:30
【问题描述】:

我想遍历我的数据库并查找在某个时间段之前(例如 5 天前或 3 天前)放置的每个项目,并在每次运行脚本时自动向用户发送一封电子邮件。因此,如果用户 5 天没有被激活,我希望脚本每天运行并检查自用户创建以来的时间是 5 天还是 3 天或其他什么。

我该如何在 Rails 中做到这一点?

这是我目前所拥有的:

定义发送提醒

@users = User.where :activated => false
@message= "Hi"
@users.each do |n|

   ActMailer.remind_users(n, current_user, @message).deliver

end

redirect_to current_user, :notice => 'Reminders were successfully sent'

结束

谢谢

【问题讨论】:

  • 这是我目前所拥有的:def send_reminders @users = User.where :activated => false @message= "Hi" @users.each do |n| ActMailer.remind_users(n, current_user, @message).deliver end redirect_to current_user, :notice => 'Reminders were successfully sent' end

标签: ruby-on-rails email timestamp


【解决方案1】:

通过一点点cron(推荐whenever gem),就可以运行这样的东西了。

您的用户类中可能有一些内容,例如:

class User < ActiveRecord::Base
  REMINDER_TIME_IN_DAYS = 5

  scope :unactivated, where(:active => false)
  scope :unreminded,  where("reminded = ? AND created_at < ?", true, REMINDER_TIME_IN_DAYS.days.ago)

  def self.send_reminders_to_unactivated_users
    User.unactivated.unreminded.each(&:send_activation_reminder)
  end
end

然后在 schedule.rb 文件中的任何时候:

every 1.day, :at => "12:00 am" do
  User.send_reminders_to_unactivated_users
end

【讨论】:

  • 如何在没有 Cron 的情况下手动执行此操作?我将每两天定期运行一次该函数,我只想让该函数返回 5 天前创建但仍处于未激活状态的用户..谢谢!
  • @NosayrYassin 仔细阅读了代码。你所需要的就在那里。
  • 你可以手动调用 User.send_reminders_to_unactivated_users。
  • 我将把它包装在一个 rake 任务中以实际拨打电话,但这个答案对我来说很有意义。
  • 对,我会将它包装在 cron 和 rake 中。 :D
猜你喜欢
  • 2015-04-29
  • 1970-01-01
  • 2011-10-25
  • 1970-01-01
  • 2015-08-26
  • 1970-01-01
  • 1970-01-01
  • 2017-06-11
  • 1970-01-01
相关资源
最近更新 更多