Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't schema.rb formatted correctly in rails 5.1.0?

Previously schema.rb was a good place to quickly see what column defaults were and whether or not they could be nullable, but now it's messy. For example, here is a user table:

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

And now it looks horrible like this:

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

Why did this happen and how can I fix it while keeping the good changes, like id: :serial and implicit btree?

like image 237
zachaysan Avatar asked May 04 '17 15:05

zachaysan


1 Answers

It was changed on purpose in this commit.

Because I look at schema.rb at least 50 times a day to see this type of information I'm going to write a tool later tonight to format it nicely while retaining the positive changes.

I'll post a link to it here once it's ready. Bug me here if I forget to post it.

Edit:

I created the script, but it's pretty brittle. I'm transforming the string output to new string output and I'm not confident I've hit all the edgecases. If you want to risk it reach out to me and I'll give you the current working version of the rake task, but it's not exactly great.

Edit2:

I've been using my hacky script for some time now without issue. If you want to add it to your project, feel free to copy it into a rake task.

Edit3:

I've switched to a SQL schema because it better encompasses what we generally want when working in production / testing. I still wanted to read the schema.rb while developing though so what I did was the following, which is working great and is less risky:

# 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
like image 179
zachaysan Avatar answered Oct 27 '22 12:10

zachaysan