Question

I'm assuming that whenever the rails app needs to construct the database, it will do so by going through all the migration files in order by timestamp. Is this correct?

Or is there some other reason?

Was it helpful?

Solution

No - when constructing the database from scratch, you should just use the schema file, located in schema.rb. You can create a database schema from this using rake db:schema:load.

The point of keeping migrations around is that if someone checks out one version of your project, and then a month later they want to update it to the latest version, they need to know incrementally how to get from the database structure then to the database structure now - without losing any data. So they can just run the migrations between those two points, which will transform the database step-by-step into the up-to-date version.

OTHER TIPS

You can safely delete them. If you do and you need to wipe the database and start again you can use rake db:schema:load to recreate the database.

Other than the mentioned reasons, it can help you specify what version of your migration you want to rollback, via rake db:rollback STEP=1 read documentation

Migration files give you a step-by-step of what was done with the db & when

If you move your app to another host, it helps you reconstruct the database, pin-point where problems arose, and generally gives you a much more robust way to populate & evolve the database over time

From the migrations documentation:

Migrations are a convenient way to alter your database schema over time in a consistent and easy way. They use a Ruby DSL so that you don't have to write SQL by hand, allowing your schema and changes to be database independent.

You can think of each migration as being a new 'version' of the database. A schema starts off with nothing in it, and each migration modifies it to add or remove tables, columns, or entries. Active Record knows how to update your schema along this timeline, bringing it from whatever point it is in the history to the latest version. Active Record will also update your db/schema.rb file to match the up-to-date structure of your database.

To me, it's basically a way to keep your database structure constructed correctly, even whilst migrating over different server


Answer

To answer your question, there are a number of rake methods you can use to rebuild your db:

  • db:migrate runs (single) migrations that have not run yet.
  • db:create creates the database db:drop deletes the database
  • db:schema:load creates tables and columns within the (existing) database following schema.rb

  • db:setup does db:create, db:schema:load, db:seed

  • db:reset does db:drop, db:setup

If you want to create the db from scratch, you'll have to run a combination of rake db:create, rake db:migrate and others

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top