How do I run rake tasks within my rails application

后端 未结 5 909
青春惊慌失措
青春惊慌失措 2020-12-24 08:47

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

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-24 09:39

    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 :-

    require 'rake'
    
    class SomeModel 

    Note: in Rails 4+, you'll use Rails.root instead of RAILS_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

提交回复
热议问题