我正在尝试将Whenever gem 实现到我的 RoR 5 应用程序中。每年一次,我希望它在我的“用户”模型中运行一个方法,但出于测试目的,我每分钟运行一次,如下所示:
时间表.rb:
set :output, "/home/ubuntu/workspace/log/cron.log"
every 1.minute do
runner "User.(methodhere)"
end
用户.rb:
def (methodhere)
User.all.each do |user|
user.update(remaining_days: user.total_days)
end
end
在多个地方,我读到有时 cronjobs 在开发模式下无法正常运行,因此我跳过所有的步骤将我的应用程序置于生产模式,但这并没有帮助。
然后我发现您可以在命令行中手动运行这些作业,然后我尝试使用发现的命令来执行此操作:
whenever --update-cron
然后
crontab -l
显示
# Begin Whenever generated tasks for:
/home/ubuntu/workspace/config/schedule.rb
* * * * * /bin/bash -l -c 'cd /home/ubuntu/workspace && bundle exec bin/rails
runner -e production '\''User.year_days_reset'\'' >>
/home/ubuntu/workspace/log/cron.log 2>&1'
正在运行
/bin/bash -l -c 'cd /home/ubuntu/workspace && bundle exec bin/rails
runner -e production '\''User.(methodhere)'\'' >>
/home/ubuntu/workspace/log/cron.log 2>&1'
在日志中留下一个错误,如下所示:
Please specify a valid ruby command or the path of a script to run.
Run 'bin/rails runner -h' for help.
undefined method `(methodhere)' for User (call 'User.connection' to
establish a connection):Class
许多谷歌搜索都没有给我留下任何结果。
注意:在 Rails 控制台中手动运行我的方法(此处的方法)可以完美地按照我的意愿运行。我是 RoR 的一名非常新的开发人员,因此我们将不胜感激任何有关此事的指导,谢谢!
编辑:@maxpleaner 指出我在 User.new.(methodhere) 中缺少 .new,这修复了错误,但是我有一个新问题。我在 Schedule.rb 中的代码似乎没有执行任何操作,因为它应该每分钟发生一次,但它什么也没做。
最佳答案
你必须有一个 User 类方法
class User
def self.method
...
end
end
这样你就可以在调度文件中使用 User.method 了。
关于ruby-on-rails - 每当 Gem - 用户未定义方法 '(methodhere)'(调用 'User.connection' 建立连接):Class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49759999/