Rails 如何跟踪数据库的哪些迁移已经运行?

根据 Rails doc: http://guides.rubyonrails.org/migrations.html

“ Active Record 跟踪已经运行的迁移,因此您所要做的就是更新源代码并运行 rake db: shift。”

ActiveRecord 实际上是如何做到这一点的? ActiveRecord 在哪里存储数据?

我怀疑这可能存储在数据库本身? 在一个表的地方。

在我的开发机器上,我运行了所有的迁移。然后使用 mysqldump 复制生产数据库。然后我运行“ rake db: shift: status”,它正确地显示了需要在生产数据库上运行的迁移。

我曾经认为 ActiveRecord 使用时间戳跟踪上一次迁移运行。但我认为这是不正确的,因为 ActiveRecord 正确地运行从另一个代码分支合并进来的“旧”迁移。

会不会有内部人员知道这些细节? 谢谢

19822 次浏览

Rails creates a table in your database called schema_migrations to keep track of which migrations have run.

The table contains a single column, version. When Rails runs a migration, it takes the leading digits in the migration's file name and inserts a row for that "version", indicating it has been run. If you roll back that migration, Rails will delete the corresponding row from schema_migrations.

For example, running a migration file named 20120620193144_create_users.rb will insert a new row with a version of 20120620193144 into the schema_migrations table.

You are free at any point to introduce migrations with earlier versions. Rails will always run any new migrations for which there is not a corresponding row in schema_migrations. The leading digits don't have to be a timestamp, you could call your migration 001_blah.rb. Earlier versions of Rails used this format, and used sequential numbering for newly generated migrations. Later versions have switched to timestamps to help prevent multiple developers from independently generating migrations with the same number.