Schema.rb 是做什么的?

我曾经认为 Rails项目中的 db/schema.rb存储了数据库模式,这样 ActiveRecord就可以知道它有哪些表/列。

但是早些时候,我惊讶地注意到,我的项目正常运行后,我删除 db/schema.rb

那么,既然 Rails可以在没有它的情况下工作,那么 schema.rb到底是做什么的呢?

33401 次浏览

The schema.rb serves mainly two purposes:

  1. It documents the final current state of the database schema. Often, especially when you have more than a couple of migrations, it's hard to deduce the schema just from the migrations alone. With a present schema.rb, you can just have a look there. ActiveRecord itself will indeed not use it. It will introspect the database during runtime as this is much safer than to expect users to keep the schema.rb up-to-date. However to avoid confusion of your developers, you should always maintain a file that is up-to-date with your migrations.

  2. It is used by the tests to populate the database schema. As such a rake db:schema:dump is often run as part of the rake test:prepare run. The purpose is that the schema of the test database exactly matches the current development database.

Rails Documentation / 6.1 What are Schema Files for?

Migrations, mighty as they may be, are not the authoritative source for your database schema. That role falls to either db/schema.rb or an SQL file which Active Record generates by examining the database. They are not designed to be edited, they just represent the current state of the database.

There is no need (and it is error prone) to deploy a new instance of an app by replaying the entire migration history. It is much simpler and faster to just load into the database a description of the current schema.

For example, this is how the test database is created: the current development database is dumped (either to db/schema.rb or db/structure.sql) and then loaded into the test database.

Schema files are also useful if you want a quick look at what attributes an Active Record object has. This information is not in the model's code and is frequently spread across several migrations, but the information is nicely summed up in the schema file. The annotate_models gem automatically adds and updates comments at the top of each model summarizing the schema if you desire that functionality.

Rails documents have you covered.