简体   繁体   中英

how to run rake task using rails migration

I want to run rake task using migration because we want when a user run rails db:migrate then this task will be run through migration.

my rake task is:

namespace :task_for_log do

  desc "This task set by default as current date for those logs where log_date is nil"
  task set_by_default_date_of_log: :environment do
    Log.where("log_date IS NULL").each do |log|
      log.update_attributes(log_date: log.created_at.to_date)
    end
  end

end

please guide what will be migration that run this task, any body here who will be save my life??

Migrations are really just Ruby files following a convention, so if you want to run a rake task inside of them you can just call the Rake class.

class ExampleMigration < ActiveRecord::Migration[5.0]
  def change
    Rake::Task['task_for_log'].invoke
  end
end

However, migration files should be used specifically to handle the database schema. I would rethink how you are approaching the problem for a better solution. For example, you could run a SQL statement that updates your log attributes instead of calling a rake task.

class ExampleMigration < ActiveRecord::Migration[5.0]
  def change
    execute <<-SQL
      UPDATE logs SET log_date = created_at WHERE log_date IS NULL
    SQL
  end
end

References:

If you want to run your task after you run db:migrate automatically, you can use enhance .

Rake::Task['db:migrate'].enhance do
  # This task runs after every time you run `db:migrate`
  Rake::Task['task_for_log:set_by_default_date_of_log'].invoke
end

For a rails application, you can put this anywhere inside lib/tasks folder or put your task inline (inside of the .enhance do block)

You can go as @joseph mention better solution! Or create custom task for it.

rake:

rake cm:set_by_default_date_of_log

task:

#lib/tasks/cm.rake
#custom_migration
namespace :cm do
  desc "This task set by default as current date for those logs where log_date is nil"
  task set_by_default_date_of_log: ['db:migrate'] do
    Log.where("log_date IS NULL").each do |log|
      log.update_attributes(log_date: log.created_at.to_date)
    end
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM