I would like to run a Rake task using migration in Rails. Every time the command rails db:migrate
is executed the task will run via migration.
The current Rake task is as follows.
namespace :task_for_log do
desc 'This task sets current date as a default for 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
How do I use a migration file to run that task?
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: