从 rake 任务访问 Rails 模型 [英] accessing rails models from rake task

查看:45
本文介绍了从 rake 任务访问 Rails 模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 rails rake 任务访问模型对象?

How can I access model objects from rails rake task?

如果我在我的 rake 中初始化我的 rufus 调度程序 $scheduler = Rufus::Scheduler.start_new 那个调度程序会保持活动状态,因为它来自一个 rake 任务吗?

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?

推荐答案

要在 rake 任务中访问 rails 模型,您需要加载 :environment.

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

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

您不会在任务中调用调度程序,反之亦然.您需要启动 Rufus 调度程序,然后从它们调用您的 rake 任务.

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.

你需要先

# other require statements ...
require 'rake'

# ...

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

这篇关于从 rake 任务访问 Rails 模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆