如何在 Rails 应用程序中运行 rake 任务
我想要做什么:
在 model.rb 中,在 after_commit 中,我想运行 rake 任务 ts:reindex
ts:reindex 通常与 rake ts:index 一起运行
What I want to do:
In a model.rb, in after_commit, I want to run rake task ts:reindex
ts:reindex is normally run with a rake ts:index
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您希望此 rake 代码在请求周期内运行,那么您应该避免通过
system
或任何 exec 系列(包括反引号)运行 rake,因为这将启动一个新的 ruby 解释器并重新加载 Rails 环境每次被调用时。相反,您可以直接调用 Rake 命令,如下所示:-
注意:在 Rails 4+ 中,您将使用
Rails.root
而不是RAILS_ROOT
。然后只需使用 SomeModel.run_rake("ts:reindex")
这里的关键部分是
require rake
并确保加载包含任务定义的文件。大多数信息来自 http://railsblogger.blogspot.com/2009/03/in -queue_15.html
If you wish this rake code to run during the request cycle then you should avoid running rake via
system
or any of the exec family (including backticks) as this will start a new ruby interpreter and reload the rails environment each time it is called.Instead you can call the Rake commands directly as follows :-
Note: in Rails 4+, you'll use
Rails.root
instead ofRAILS_ROOT
.And then just use
SomeModel.run_rake("ts:reindex")
The key parts here are to
require rake
and make sure you load the file containing the task definitions.Most information obtained from http://railsblogger.blogspot.com/2009/03/in-queue_15.html
此代码会自动为您的 Rails 应用程序加载 Rake 任务,您甚至不知道您的应用程序是如何命名的:)
This code automagically loads the Rake tasks for your Rails application without you even knowing how your application is named :)
然后只需使用 SomeModel.run_rake("ts:reindex") 即可。
And then just use
SomeModel.run_rake("ts:reindex")
.我遇到了同样的问题,由于加载文件错误,无法在我的控制器中使用 Rails 4 项目获得可接受的答案。 这篇文章给了我一个可行的解决方案:
I had this same issue and couldn't get the accepted answer to work in my controller with a Rails 4 project due to a load file error. This post gave me a working solution:
您尝试过“rake ts:reindex”吗?
Have you tried `rake ts:reindex`?