Rails - Can I run migration methods in a general rake program?

I know that this is not the best practice, and most likely it should not even be used, because this is what migrations are used for, but I was wondering if it is possible to execute specific migration commands in a regular rake command. Sort of:

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

thank

+3
source share
2 answers

In your rake tasks you can perform arbitrary pseudo-migrations:

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

If you do a lot of this, use a 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
+6
source

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 here it is important to include the migration class, and then send the method that you want to run.

ActiveRecord::Migration @tadman

+1

Source: https://habr.com/ru/post/1757013/


All Articles