RoR: Using CRON and Actionmailer to send daily email updates to all users

actionmailer, cron, ruby-on-rails

Solution

I usually just write a rake task and add it to CRON.

The rake task will look like this:

namespace :notifications do
  desc "Sends notifications"
  task :send => :environment do
    MyModel.all_users_to_notify.each do |u|
      MyMailer.notification(u).deliver
    end
  end
end

And your crontab should look like this:

RAILS_ENV=production
HOME=/path/to/your/rails/app
PATH=/path/to/ruby/binaries

30 17 * * * rake notifications:send

Problem

What exactly would be the best way to go about using a cron task to send daily e-mails of updates to all users on my network? The e-mail would be made up of different information from multiple models. I want to do something like "1 new friend requests : name ..." from the request model and user model and "There are 3 upcoming events from your friends: event name hosted by name..." from the event and user model. I realize this is a common task but I didn't see much information on it, so any general tips about doing something like this would be greatly appreciated! Side note: I will be using the Heroku daily cron plug-in to accomplish this if that matters (although I don't think it should).

Original source