使用 rake db:直接迁移、普通 SQL
使用 rake db:migrate 加载普通 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
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' migrations 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是完全可以接受的,并且没有任何问题,只要您确信您的 up 和 down 函数相互镜像即可。为了便于阅读,我建议执行以下操作:
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:
您可以通过使用
standalone-migrations
宝石。安装 gem 后,将以下行添加到您的
Rakefile
中以启用rake db:*
任务:之后,您只需像平常一样设置迁移:
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 enablerake db:*
tasks:After that you simply setup your migrations as you would normally do: