简体   繁体   English

Rails 3.2:Ruby日期逻辑

[英]Rails 3.2: Ruby date logic

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. 我有一个Rails应用程序,需要从数据库中的多个模型中检查日期(dd / mm),并在每个日期的2周之前,1周之前和1天之前触发邮件。 How could I write this logic in my app (rails 3.2)? 如何在我的应用中编写此逻辑(Rails 3.2)?

*Note - I plan on using a rake task to check whether and mails need to be sent out. *注意-我计划使用rake任务来检查是否需要发送邮件。

You could do this with scopes: 您可以使用范围:

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

The date ranges grab all models with a date in the 2 weeks before, you can adjust the endpoints as necessary, obv. 日期范围会抢占所有具有2周前日期的模型,您可以根据需要调整端点。

2 weeks before, compare date with this: 在2周前,将日期与此:

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

1 week, to this: 1周,到此:

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

Try in your console and see the results. 在您的控制台中尝试并查看结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM