views:

21

answers:

2

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

A: 

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

jpemberthy
Including an arbitrary migration seems odd. Why not just bang against ActiveRecord::Migration directly?
tadman
Yup You'r right, I'm gonna edit the answer, thanks!
jpemberthy
For some reason, I was under the assumption that if I used the ActiveRecord::Migration class directly, it would attempt to insert a record in the schema_migrations table
gmoniey
I believe the only way you can trigger an addition to the schema_migrations table is to define an ActiveRecord::Migration.up method and run it.
tadman
+1  A: 

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
tadman
Good to know. I didn't realize that those functions were a part of the connection class.Thanks.
gmoniey
There's a lot of good stuff in there if you look around. I'm a big fan of the connection object, especially things like select_values.
tadman