2011-02-08 85 views
6

使用rake db:migrate加載vanilla SQL會涉及哪些陷阱?使用rake db:直接遷移,vanilla SQL

我正在使用的業務需求不允許使用默認的Rails遷移。但是我仍然需要跟蹤更改,輕鬆更改數據庫DDL以及Rails的遷移所提供的其他內容。

所以遷移文件看起來像:

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 

回答

17

這是完全可以接受的,也沒有陷阱,只要你有信心,你的向上和向下的功能互爲鏡像。我建議做是爲了便於閱讀以下內容:

 
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 
0

您可以通過使用standalone-migrations gem使用了Rails在非軌道項目移植的方法。

安裝您以下行添加到您的Rakefile寶石後,使rake db:*任務:

require 'standalone_migrations' 
StandaloneMigrations::Tasks.load_tasks 

後,您只需設置你的遷移,你通常會做:

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

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