为什么在Rails 5.1.0中schema.rb格式不正确?

7

以前,schema.rb是快速查看列默认值和它们是否可为空的好地方,但现在它变得凌乱。例如,这是一个用户表:

create_table "users", force: :cascade do |t|
  t.string   "name",                              null: false
  t.string   "email",                             null: false
  t.string   "locale",          default: "en-ca", null: false
  t.string   "password_digest",                   null: false
  t.datetime "created_at",                        null: false
  t.datetime "updated_at",                        null: false
  t.index ["email"], name: "index_users_on_email", unique: true, using: :btree
end

现在它看起来很糟糕,像这样:

create_table "users", id: :serial, force: :cascade do |t|
  t.string "name", null: false
  t.string "email", null: false
  t.string "locale", default: "en-ca", null: false
  t.string "password_digest", null: false
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.index ["email"], name: "index_users_on_email", unique: true
end

为什么会发生这种情况,如何在保留诸如 id: :serial 和隐式 btree 等好变化的同时解决它?
1个回答

7

这是一个有意的更改,包含在此次提交中。

因为我每天至少要查看50次schema.rb以获取这种信息,所以今晚我将编写一个工具来格式化它并保留积极的更改。

一旦准备好,我会在这里发布链接。如果我忘记发布,请在此提醒我。

编辑:

我创建了脚本,但它相当脆弱。我正在将字符串输出转换为新的字符串输出,并且我不确定是否已经涵盖了所有边缘情况。如果你想冒险使用它,请联系我,我将给你当前工作版本的rake任务,但它并不完美。

编辑2:

我已经使用我的hacky脚本很长时间了,没有出现问题。如果您想将其添加到项目中,请随意将其复制到rake任务中。

编辑3:

我已经切换到SQL模式,因为它更好地涵盖了我们在生产/测试中通常想要的内容。不过,在开发时我仍然想阅读schema.rb,所以我做了以下操作,效果很好,风险较小:

# In config/application.rb
config.active_record.schema_format = :sql


# In config/environments/development.rb
config.active_record.schema_format = :ruby

# In the rake task
namespace :db do

  def cleanup_schema
    # Other code goes here
  end

  task :migrate do
    if Rails.env.development?
      cleanup_schema
    end
  end

  task :rollback do
    if Rails.env.development?
      cleanup_schema
    end
  end

  task :cleanup_schema do
    cleanup_schema
  end

end

您可能也会对 https://github.com/jakeonrails/fix-db-schema-conflicts 感兴趣,我们已经使用它很长时间来按字母顺序排序模式并标准化缩进。 - Ollie Bennett

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接