accessing rails models from rake task

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-23 17:54:45

问题


How can I access model objects from rails rake task?

If I initialize my rufus scheduler $scheduler = Rufus::Scheduler.start_new in my rake would that scheduler stay alive since it's from a rake task?


回答1:


To access a rails model in your rake task you need to load the :environment.

task :my_task => [:environment] do
  User.new #...
end

You would not call the scheduler within a task but the other way around. You need to start a Rufus scheduler and then call your rake tasks from them.

You need to first

# other require statements ...
require 'rake'

# ...

scheduler = Rufus::Scheduler.start_new
scheduler.cron "00 6 * * *" do
  Rake::Task["sometask"].invoke
end


来源:https://stackoverflow.com/questions/6455808/accessing-rails-models-from-rake-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!