我正在帮助 friend 开发 Rails 应用程序。他们有一个数据库,其中包含许多表,这些表是使用 SQL 手动添加的,而不是使用 Rails 迁移。他们已开始正常添加迁移,但需要使两者恢复同步。
如果我们现在添加迁移,它们会出错,因为这些表/列已经存在。如果我们将它们排除在外,人们就必须使用 db:schema:load 来启动和运行,然后按名称一次运行一个迁移以避免错误。我们希望避免这种情况并恢复到健康状态。
有谁知道更好的方法来使迁移与数据库同步?我们必须在不丢失任何数据的情况下执行此操作。
最佳答案
这是question with the same problem (没有投票赞成将您的答案作为重复项关闭,因为旧的答案没有可接受的答案):
解决办法是:
- Start by referencing your existing MySQL database in
database.yml
.- run
rake db:schema:dump
to generate theschema.rb
file- Paste the
create_table
methods from yourschema.rb
into a new migration, and Voila!
为了避免任何不一致,您可以随时检查该表是否已经存在,如果是,则完全跳过迁移:
class CreateTable < ActiveRecord::Migration
def change
unless ActiveRecord::Base.connection.table_exists?('table_name')
create_table :table_names do |t|
# some columns
end
end
end
end
关于mysql - 如何修复具有许多表的数据库而不使用 Rails 匹配迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39729706/