ruby-on-rails - 为什么 schema.rb 在 rails 5.1.0 中的格式不正确?

标签 ruby-on-rails ruby rails-activerecord

以前 schema.rb 是快速查看列默认值以及它们是否可以为 null 的好地方,但现在很困惑。例如,这是一个用户表:

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)的同时修复它?

最佳答案

它是在 this 中故意更改的提交。

因为我每天至少查看 schema.rb 50 次以查看此类信息,所以今晚晚些时候我将编写一个工具来很好地格式化它,同时保留积极的变化。

准备就绪后,我会在此处发布指向它的链接。如果我忘记发布,请在此处打扰我。

编辑:

我创建了脚本,但它很脆弱。我正在将字符串输出转换为新的字符串输出,但我不确定我是否遇到了所有边缘情况。 如果您想冒险与我联系,我会为您提供 rake 任务的当前工作版本,但它并不是很好。

编辑2:

我一直在使用 my hacky script一段时间以来没有问题。如果您想将它添加到您的项目中,请随时将其复制到 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

关于ruby-on-rails - 为什么 schema.rb 在 rails 5.1.0 中的格式不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43786903/

相关文章:

ruby-on-rails - Ruby 更新后 Rails 3.1rc4 Assets 管道中断?如何重新激活/配置它?

ruby-on-rails - Rails 3 + 迁移中的设计错误 : undefined method timeoutable

ruby - Ruby 中的横切日志记录

ruby-on-rails - 显示页面未能沿(rails)传递种子数据

mysql - 转换为 Float 返回 ActiveRecord::StatementInvalid: Mysql2::Error

ruby-on-rails - 无法让 Bootstrap 与 Rails 一起使用

ruby-on-rails - 未定义的方法 `gsub' 为 nil :NilClass

ruby-on-rails - 选择类别 : Rails 4 many to many association

ruby-on-rails - Ruby/Rails - 在不建模的情况下访问 "lookup"表?

ruby-on-rails - 创建失败时 Ruby on Rails Active Record 返回值?