我有两个模型,User
和 PushupReminder
,在我的 PushupReminder Controller 中有一个方法 create_a_reminder
(这是放置它的最佳位置吗?)当我向它传递用户 ID 时,我想为给定用户创建一个新的 PushupReminder 实例。我通过 user_id 列在我的 PushupReminder
表中正常工作,并且我已经测试过我可以创建提醒并通过 Rails 控制台正确发送提醒电子邮件。
这是模型代码的片段:
class User < ActiveRecord::Base
has_many :pushup_reminders
end
class PushupReminder < ActiveRecord::Base
belongs_to :user
end
以及 create_a_reminder 方法:
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
我不知道如何在我的代码中为给定用户运行 create_a_reminder
方法(最终将在我所有用户的 cron 作业中)。如果有人可以帮助我让我的想法走上正轨,我将不胜感激。
谢谢!
最佳答案
编辑:I've posted a sample Rails app here展示我在回答中谈论的内容。我还发布了 new commit, complete with comments这演示了当俯卧撑提醒也以非嵌套方式可用时如何处理它们。
毫无疑问,Paul 的方向是正确的。您需要在两个地方使用此创建 功能,如果您想将其作为 cron 作业运行,第二个很重要。
- 在您的
PushupRemindersController
中,作为User
的嵌套资源;为了通过网络创建俯卧撑提醒。 - 在 rake 任务中,它将作为 cron 作业运行。
Rails 已经为您提供了您需要的大部分代码,并且您已经在 ActiveRecord 关联中设置了大部分代码。对于 #1,在 routes.rb
中,设置 nested routes ...
# Creates routes like...
# /users/<user_id>/pushup_reminders
# /users/<user_id>/pushup_reminders/new
# /users/<user_id>/pushup_reminders/<id>
resources :users do
resources :pushup_reminders
end
你的 PushupRemindersController
应该看起来像...
class PushupRemindersController < ApplicationController
before_filter :get_user
# Most of this you'll already have.
def index
@pushup_reminders = @user.pushup_reminders
respond_with @pushup_reminders
end
# This is the important one.
def create
attrs = {
:completed => false,
:num_pushups => @user.pushups_per_reminder,
:when_sent => Time.now
}
@pushup_reminder = @user.pushup_reminders.create(attrs)
respond_with @pushup_reminder
end
# This will handle getting the user from the params, thanks to the `before_filter`.
def get_user
@user = User.find(params[:user_id])
end
end
当然,您将有一个新的
操作,它将向用户显示一个网络表单,等等。
对于第二个用例,cron
任务,设置它 as a Rake task在项目的 lib/tasks
目录中。这使您可以自由支配,通过 cron 任务设置一个在需要时执行的操作。您将拥有对所有 Rails 模型等的完全访问权限,就像 Controller 操作一样。真正的诀窍是:如果您有用于设置提醒的疯狂自定义逻辑,请将其移至 PushupReminder
模型中的操作。这样你就可以从一个 rake 任务中触发一个创建方法,一个从 Controller 中触发,你不必重复编写任何你的创建逻辑。请记住,不要重复自己 (DRY)!
我发现在设置 cron
任务时非常有用的一个 gem 是 whenever gem。 .在 Ruby 中编写您的特定于站点的 cron 作业,并获得您需要粘贴到 cron 选项卡中的内容的准确输出(如果您通过 Capistrano 部署,则 cron 作业的完全不干涉管理)!
关于ruby-on-rails - 使用关联模型的参数创建 Rails 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13537132/