データベース内のいくつかのモデルから日付(日/月)をチェックし、各日付の2週間前、1週間前、および1日前にメーラーをトリガーする必要があるRailsアプリがあります。このロジックをアプリ (Rails 3.2) でどのように記述できますか?
*注 - メールを送信する必要があるかどうかを確認するために rake タスクを使用する予定です。
データベース内のいくつかのモデルから日付(日/月)をチェックし、各日付の2週間前、1週間前、および1日前にメーラーをトリガーする必要があるRailsアプリがあります。このロジックをアプリ (Rails 3.2) でどのように記述できますか?
*注 - メールを送信する必要があるかどうかを確認するために rake タスクを使用する予定です。
スコープでこれを行うことができます:
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 週間前の日付を持つすべてのモデルを取得します。必要に応じてエンドポイントを調整できます。
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)
コンソールで試して、結果を確認してください。