Search code examples
ruby-on-railsactiverecord

Rails: what does schema.rb do?


I used to think the db/schema.rb in a Rails project stored the database schema, so that ActiveRecord can know what table/column it has.

But earlier I surprisingly noticed that my project runs normally after I delete db/schema.rb!

So, since the Rails can work without it, what does schema.rb really do?


Solution

  • 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.

    In addition to that, some people use the schema.rb to load the final schema into a database to avoid having to run a long list of migrations to setup a fresh database. This is sometimes necessary if you have an application where the previous migrations can not run cleanly with the rest of the application (e.g. because model definitions have changed between the time the migrations were added compared to the current state).

    Generally however, I would recommend to keep the migrations up-to-date with the rest of the application so that you can always start with just the migrations rather than replying on schema.rb to avoid multiple and potentially diverging "sources of truth".