The common approach to setup a rails app database is:
rake db:create db:migrate
However, you are able to construct a fresh database via a schema import. The schema of the application can be found in schema.rb file in your db directory. The import is done by:
The schema.rb is updated every time you run db:migrate and it reflects the latest schema of your application database. While both database migration and schema loading give you the same database structure as the end result, there are some key differences.
- The performance
- What happens to the existing data?
Database migration runs incrementally. It executes each migration file you have, one by one. This means if you create a table, then add a new column in the table and finally change the data type of another column, database migration executes 3 times. On the other hand, schema loading only executes the latest and final schema without going through the entire change histories journey.
Database migration keeps all your existing data if any. Schema loading gives you a fresh new database. It removes all existing data.
By knowing these differences, so when do we use database migration or schema loading?
- Database migration is used during development environment, while your database is still in the building. It is also used for updating existing production database where you want to keep existing data.
- Schema loading is used for deploying to a new database, could be development, test or production environment.
Note: There are 2 formats of schema.rb - ActiveRecord migrations and SQL. The default is ActiveRecord migrations. You can change the setting below:
config.active_record.schema_format = :sql # or :ruby