【问题标题】:rails changes schema.rb for no reasonrails 无缘无故更改 schema.rb
【发布时间】:2013-02-12 21:54:46
【问题描述】:

每次我运行rake db:migrate rails 都会决定更改我的 schema.rb 文件。在某些情况下,这是完全合理的,但在其他一些情况下,它似乎无缘无故地这样做。我感到困惑的情况是,当我从 git 中提取新迁移和 schema.rb 的新版本,然后运行 ​​rake db:migrate 时。由于此迁移附带了新版本的 schema.rb 文件,因此我不应该更新 schema.rb。然而,rails 每次都会改变它。发生这种情况时,我会发现非常愚蠢的变化,例如:

add_index "my_table", ["column1", "column2"], :name => "index_on_some_columns"

add_index "my_table", ["column2", "column1"], :name => "index_on_some_columns"

当这种情况发生时,我只需运行git checkout db/schema.rb 并继续我的生活,但这让我很恼火。它这样做有什么原因,我该如何阻止它这样做?

编辑:这是一个差异的摘录

@@ -165,12 +165,11 @@ ActiveRecord::Schema.define(:version => 20130206001907) do
     t.column "updated_at", :datetime
-    t.column "coordinates", :point, :srid => 4326
@@ -200,15 +199,16 @@ ActiveRecord::Schema.define(:version => 20130206001907) do
     t.column "something", :boolean
+    t.column "coordinates", :point, :srid => 4326
+    t.column "random_string", :string
     t.column "remote", :string
-    t.column "random_string", :string
   end

-  add_index "my_table", ["id", "foreign_id"], :name => "index_active_my_table_on_foreign_and_id"
-  add_index "my_table", ["id", "active"], :name => "index_my_table_on_active_and_id"
-  add_index "my_table", ["id", "content_modified_at"], :name => "index_my_table_on_content_modified_at_and_id"
+  add_index "my_table", ["foreign_id", "id"], :name => "index_active_my_table_on_foreign_and_id"
+  add_index "my_table", ["active", "id"], :name => "index_my_table_on_active_and_id"
+  add_index "my_table", ["content_modified_at", "id"], :name => "index_my_table_on_content_modified_at_and_id"

【问题讨论】:

  • 迁移文件中这个索引是如何定义的?
  • 在多种情况下,迁移表示add_index :my_table, ["column2", "column1"],但通过 git 提供的 schema.rb 具有相反的顺序:add_index "my_table", ["column1", "column2"]。它似乎是一致的,但现在我想知道列的相反顺序是如何进入代码的。这可能很幼稚,但这可能与同时使用 linux/mac 有关系吗?
  • 我通常把 db/schema.rb 放在 .gitignore 中

标签: ruby-on-rails rails-migrations


【解决方案1】:

由于此次迁移附带了新版本的 schema.rb 文件,我不应该更新 schema.rb。

这是不准确的。

每次 Rails 运行迁移时,它都会使用数据库作为源更新 schema.rb 文件。它不查看现有的schema.rb 文件,它只是使用数据库中的信息并覆盖它。

看来真正的问题是在两个不同的环境(Ruby、Rails、MySQL、操作系统的不同组合)中运行相同的迁移可能会在生成schema.rb 文件时产生不同的结果。

解决方案是确保每个签入代码的人都尽可能使用相同的软件版本。如果不可能(因为这是 Windows 与 Linux 与 Mac 的区别,而且您不想更改操作系统),您只需要处理不便。

【讨论】:

  • 感谢您为我澄清这一点。如果文件实际上没有改变,我将不得不看看我是否可以破解一些可以绕过更改文件的东西!
【解决方案2】:

对我来说,解决方案是先创建一个rake db:schema:load。而且rake db:migrate 无缘无故地停止更改我的schema.rb

注意:rake db:schema:load 将删除您现有数据的所有,并根据现有 schema.rb 重新创建数据库。

【讨论】:

    猜你喜欢
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 2011-08-05
    • 2020-04-09
    • 1970-01-01
    • 2017-04-11
    相关资源
    最近更新 更多