使用 rake db:直接迁移、普通 SQL

发布于 2024-10-16 11:49:12 字数 444 浏览 2 评论 0原文

使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

逆光下的微笑 2024-10-23 11:49:12

这是完全可以接受的,并且没有任何问题,只要您确信您的 up 和 down 函数相互镜像即可。为了便于阅读,我建议执行以下操作:

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

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
拥抱影子 2024-10-23 11:49:12

您可以通过使用 standalone-migrations 宝石

安装 gem 后,将以下行添加到您的 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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文