Search code examples
ruby-on-railsmigrationrake

Run rake task from rails migration file


I have a rake task that I run from the terminal using the command below.

bundle exec rake migrations:seed_us_users

I have created this migration file but I don’t know how the code should be to run this rake task.

class AddNewUsers < ActiveRecord::Migration[5.1]
  def change
  end
end

Solution

  • You can execute a rake task from within a loaded Rails environment with either

    Rake::Task['migrations:seed_us_users'].invoke or Rake::Task['migrations:seed_us_users'].execute
    

    You can pass data to the task inside of the invoke or execute method. Example:

    Rake::Task['migrations:seed_us_users'].invoke(params)
    

    For more details please check https://sampatbadhe.medium.com/rake-task-invoke-or-execute-419cd689c3bd