简体   繁体   English

如何使用 rails 迁移运行 rake 任务

[英]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.我想使用迁移运行 rake 任务,因为我们希望当用户运行rails db:migrate此任务将通过迁移运行。

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.迁移实际上只是遵循约定的 Ruby 文件,因此如果您想在其中运行 rake 任务,您只需调用 Rake 类即可。

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.例如,您可以运行更新日志属性的 SQL 语句,而不是调用 rake 任务。

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 .如果您想在自动运行db:migrate运行您的任务,您可以使用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)对于 rails 应用程序,您可以将其放在lib/tasks文件夹内的任何位置或将您的任务内联(在.enhance do块内)

You can go as @joseph mention better solution!你可以去@joseph 提到更好的解决方案! 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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