1

I am trying to run the command rake db:migrate using a sidekiq worker but it seems like it just won't work and I am curious if there is a way to do this or not. I am creating a scaffold using sidekiq but cannot migrate it afterwards

This works

class ScaffoldGeneratorWorker
  include Sidekiq::Worker

    def perform(id)
      `rails g scaffold test_#{id} title:string body:text slug:string visible:boolean`
    end
end

But I cannot get this to run afterwards and work

class DatabaseMigrationWorker
  include Sidekiq::Worker

  def perform
    `rake db:migrate`
  end
end

Is this possible, and, if so, how can I get it to work. Any help is greatly appreciated.

Rockwell Rice
  • 3,376
  • 5
  • 33
  • 61

3 Answers3

12

First you should load rake tasks, then invoke:

class DatabaseMigrationWorker
  include Sidekiq::Worker

  def perform
     Name_Of_Your_App::Application.load_tasks
     Rake::Task['db:migrate'].invoke
  end
end
Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103
5

This code automagically loads the Rake tasks for your Rails application without you even knowing how your application is named (this was the case for me). It also makes the code easier to share between various Rails projects.

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

If you need to invoke the Rake task with parameters, you can simply pass them in through the invoke method (https://www.rubydoc.info/gems/rake/Rake%2FTask:invoke):

Rake::Task['db:migrate'].invoke(params)

snrlx
  • 4,987
  • 2
  • 27
  • 34
0

Did you try adding require 'rake' at the top of your file?

a possible duplicate of How do I run rake tasks within my rails application

Community
  • 1
  • 1
John Hayes-Reed
  • 1,358
  • 7
  • 13