我正在尝试使用每当 gem 创建一个 cron 作业来向用户发送生日提醒,并且我希望这个 cron 每天运行。
我的每当 gem 工作时,但我的 cron 作业总是出错。我试图在 Rails 控制台中调用 Controller 方法来解决这个问题,但我不断收到错误,我不确定为什么。
我有这个 Controller :
class BirthdayRemindersController < ApplicationController
include ApplicationHelper
# cron job that sends birthday reminders
def send_birthday_email_reminders
users = User.all
email_addresses = []
users.each_with_index do |user, i|
if user.user_details.birthday_reminders == true
email_addresses[i] = get_primary_email(user)
end
end
p email_addresses
users.each do |user|
if user.user_details.birthday == Date.today
p "reminder sent"
send_birthday_reminders(user, email_addresses)
end
end
end
end
在 Rails 控制台中,我尝试了这两种方法,但都出错了。
Toms-Mac-mini:famnfo TomCaflisch$ rails c
Loading development environment (Rails 3.2.9)
irb(main):001:0> BirthdayRemindersController.send_birthday_email_reminders
NoMethodError: undefined method `send_birthday_email_reminders' for BirthdayRemindersController:Class
from (irb):1
from /Users/TomCaflisch/.rvm/gems/ruby-1.9.3-p327@famnfo/gems/railties-3.2.9/lib/rails/commands/console.rb:47:in `start'
from /Users/TomCaflisch/.rvm/gems/ruby-1.9.3-p327@famnfo/gems/railties-3.2.9/lib/rails/commands/console.rb:8:in `start'
from /Users/TomCaflisch/.rvm/gems/ruby-1.9.3-p327@famnfo/gems/railties-3.2.9/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
irb(main):002:0> BirthdayReminders.send_birthday_email_reminders
NameError: uninitialized constant BirthdayReminders
from (irb):2
from /Users/TomCaflisch/.rvm/gems/ruby-1.9.3-p327@famnfo/gems/railties-3.2.9/lib/rails/commands/console.rb:47:in `start'
from /Users/TomCaflisch/.rvm/gems/ruby-1.9.3-p327@famnfo/gems/railties-3.2.9/lib/rails/commands/console.rb:8:in `start'
from /Users/TomCaflisch/.rvm/gems/ruby-1.9.3-p327@famnfo/gems/railties-3.2.9/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
irb(main):003:0>
我错过了什么?我没有为此 Controller 定义路由,因为我不希望任何人能够通过网络浏览器访问它
最佳答案
Controller 上的方法是实例方法,而不是类方法。类方法是用self.
定义的。很难从控制台触发 Controller 操作,因为您错过了整个上下文。您没有 session 、没有请求、没有响应。所有这些都使得在 Controller 操作内使用代码变得困难。如果您需要从外部触发代码(控制台、机架任务、其他代码)。您应该将代码提取到它自己的类中。
关于ruby-on-rails - Rails 尝试从控制台调用 Controller 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14172469/