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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With