我想做的事情:
在 model.rb 中的 after_commit 中,我想要运行 rake 任务 ts:reindex。
通常需要使用 rake ts:index 来运行 ts:reindex。
我想做的事情:
在 model.rb 中的 after_commit 中,我想要运行 rake 任务 ts:reindex。
通常需要使用 rake ts:index 来运行 ts:reindex。
如果您希望此rake代码在请求周期内运行,则应避免通过system
或任何exec家族(包括反引号)运行rake,因为每次调用都会启动一个新的Ruby解释器并重新加载rails环境。
相反,您可以直接调用Rake命令,如下所示:
require 'rake'
class SomeModel <ActiveRecord::Base
def self.run_rake(task_name)
load File.join(RAILS_ROOT, 'lib', 'tasks', 'custom_task.rake')
Rake::Task[task_name].invoke
end
end
注意:在Rails 4及以上版本中,您将使用Rails.root
而不是RAILS_ROOT
。SomeModel.run_rake("ts:reindex")
。require rake
并确保加载包含任务定义的文件。这段代码可以自动加载你的Rails应用程序的Rake任务,而无需知道应用程序的名称 :)
class MySidekiqTask
include Sidekiq::Worker
def perform
application_name = Rails.application.class.parent_name
application = Object.const_get(application_name)
application::Application.load_tasks
Rake::Task['db:migrate'].invoke
end
end
require 'rake'
RailsApp::Application.load_tasks
class SomeModel <ActiveRecord::Base
def self.run_rake(task_name)
load File.join(Rails.root, 'lib', 'tasks', 'custom_task.rake')
Rake::Task[task_name].invoke
end
end
然后只需使用SomeModel.run_rake("ts:reindex")
。
我遇到了同样的问题,在使用Rails 4项目中,由于文件加载错误,无法在我的控制器中使用被接受的答案。这篇文章给了我一个有效的解决方案:
def restart_search
require 'rake'
spec = Gem::Specification.find_by_name 'thinking-sphinx'
load "#{spec.gem_dir}/lib/thinking_sphinx/tasks.rb"
Rake::Task["ts:stop"].execute
Rake::Task["ts:start"].execute
respond_to do |format|
format.js { head :ok }
end
end
.execute
而不是.invoke
才能让它工作,至少对我来说是这样。 - kakubeiRake::Task.clear
,然后调用<YourAppModule>::Application.load_tasks
。 - Anthony ERails.application.load_tasks
。 - Stephen