I have two models, User and PushupReminder, and a method create_a_reminder in my PushupReminder controller (is that the best place to put it?) that I want to have create a new instance of a PushupReminder for a given user when I pass it a user ID. I have the association via the user_id column working correctly in my PushupReminder table and I’ve tested that I can both create reminders & send the reminder email correctly via the Rails console.
Here is a snippet of the model code:
class User < ActiveRecord::Base
has_many :pushup_reminders
end
class PushupReminder < ActiveRecord::Base
belongs_to :user
end
And the create_a_reminder method:
def create_a_reminder(user)
@user = User.find(user)
@reminder = PushupReminder.create(:user_id => @user.id, :completed => false, :num_pushups => @user.pushups_per_reminder, :when_sent => Time.now)
PushupReminderMailer.reminder_email(@user).deliver
end
I’m at a loss for how to run that create_a_reminder method in my code for a given user (eventually will be in a cron job for all my users). If someone could help me get my thinking on the right track, I’d really appreciate it.
Thanks!
Edit: I’ve posted a sample Rails app here demonstrating the stuff I’m talking about in my answer. I’ve also posted a new commit, complete with comments that demonstrates how to handle pushup reminders when they’re also available in a non-nested fashion.
Paul’s on the right track, for sure. You’ll want this create functionality in two places, the second being important if you want to run this as a cron job.
PushupRemindersController, as a nested resource for aUser; for the sake of creating pushup reminders via the web.Most of the code you need is already provided for you by Rails, and most of it you’ve already got set in your ActiveRecord associations. For #1, in
routes.rb, setup nested routes…And your
PushupRemindersControllershould look something like…Of course, you’ll have a
newaction that will present a web form to a user, etc. etc.For the second use case, the
crontask, set it up as a Rake task in yourlib/tasksdirectory of your project. This gives you free reign to setup an action that gets hit whenever you need, via a cron task. You’ll have full access to all your Rails models and so forth, just like a controller action. The real trick is this: if you’ve got crazy custom logic for setting up reminders, move it to an action in thePushupRemindermodel. That way you can fire off a creation method from a rake task, and one from the controller, and you don’t have to repeat writing any of your creation logic. Remember, don’t repeat yourself (DRY)!One gem I’ve found quite useful in setting up
crontasks is the whenever gem. Write your site-specific cron jobs in Ruby, and get the exact output of what you’d need to paste into a cron tab (and if you’re deploying via Capistrano, total hands-off management of cron jobs)!