简体   繁体   中英

Rails — Possible to run migration methods in generic rake task?

I know this is not best practice, and most likely shouldn't even be used, as thats what migrations are used for, but I was wondering if its possible to execute migration specific commands in a regular rake task. Something like:

namespace :dummy do
    task :update => :environment do
      add_column :users, :deleted, :boolean, { :null => false, :default => false }
   end
end

Thanks

It is possible to run arbitrary pseudo-migrations in your rake tasks:

namespace :dummy do
  task :update => :environment do
    ActiveRecord::Base.connection.add_column :users, :deleted, :boolean, :null => false, :default => false
  end
end

If you're doing a lot of that sort of thing, use short-hand:

namespace :dummy do
  task :update => :environment do
    c = ActiveRecord::Base.connection

    c.add_column :users, :deleted, :boolean, :null => false, :default => false
  end
end

Yes, you should do something like this:

namespace :dummy do
  task :update => :enviroment do
    ActiveRecord::Migration.send(:add_column, :users, :deleted, :boolean, { :null => false, :default => false })
  end
end

Not tested, but the important thing here is to include the migration class and then send the method you wish to run.

UPDATED to use ActiveRecord::Migration directly via @tadman

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