0

I have a rails app where I need to check date(s)(dd/mm) from several models in my database and trigger a mailer 2 weeks before, 1 week before, and 1 day before each date. How could I write this logic in my app (rails 3.2)?

*Note - I plan on using a rake task to check whether and mails need to be sent out.

4

2 回答 2

2

您可以使用范围执行此操作:

class MyModel < ActiveRecord::Base
  scope :two_weeks_before, lambda{|the_date| where('my_date between ? and ?', 2.weeks.until(the_date), the_date)}
  scope :one_week_before, lambda{|the_date| where('my_date between ? and ?', 1.week.until(the_date), the_date)}
  scope :the_day_before, lambda{|the_date| where('my_date between ? and ?', 1.day.until(the_date), the_date)}
  scope :undelivered, where(:delivered => false)
end

# usage:
MyModel.two_weeks_before(Date.tomorrow).undelivered.all.each do |model|
  MyMailer.notification(model).deliver
  model.update_attribute(:delivered, true)
end

日期范围获取日期在 2 周前的所有模型,您可以根据需要调整端点,obv。

于 2012-06-20T17:10:05.323 回答
1

2 周前,将日期与此进行比较:

Model.where("my_date between ? and ?", Date.today - 15, Date.today - 14)

1周,到这个:

Model.where("my_date between ? and ?", Date.today - 8, Date.today - 7)

在您的控制台中尝试并查看结果。

于 2012-06-20T16:48:47.337 回答