开发者

Using rake db:migrate straight, vanilla SQL

What gotchas would be involved by using rake db:migrate to load vanilla SQL?

The business requirements that I am working with don't allow me to use the default Rails' migrations. But I still need to track changes, easily alter the database DDL, and the other things that Rails' migr开发者_StackOverflow中文版ations give you.

So a migration file would look like:

class AddDateToPost < ActiveRecord::Migration
  def self.up
    ActiveRecord::Base.connection.execute("ALTER TABLE `posts` ADD COLUMN date DATETIME NULL")
  end

  def self.down
    ActiveRecord::Base.connection.execute("ALTER TABLE `posts` DROP COLUMN date")
  end
end


That's perfectly acceptable and there are no gotchas, as long as you feel confident that your up and down functions mirror each other. I would suggest doing the following for readability:

class AddDateToPost < ActiveRecord::Migration
  def self.up
    execute "ALTER TABLE `posts` ADD COLUMN date DATETIME NULL"
  end

  def self.down
    execute "ALTER TABLE `posts` DROP COLUMN date"
  end
end


You can use the Rails migration methods in a non-rails project by using the standalone-migrations gem.

After installing the gem you add the following lines to your Rakefile to enable rake db:* tasks:

require 'standalone_migrations'
StandaloneMigrations::Tasks.load_tasks

After that you simply setup your migrations as you would normally do:

class AddDateToPost < ActiveRecord::Migration
  def self.up
    add_columm :posts, :date, :datetime, default: nil
  end

  def self.down
    remove_columm :posts, :date
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜