Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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??

like image 867
Rana. Amir Avatar asked Dec 18 '22 19:12

Rana. Amir


1 Answers

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:

  • Rails how to run rake task
  • https://edgeguides.rubyonrails.org/active_record_migrations.html
like image 106
Joseph Cho Avatar answered Dec 20 '22 07:12

Joseph Cho