How does rails decide if migrations are pending?
Ever wondered how rails decides if any migration is pending? If not, this tutorial will explain how it is done using a table named schema_migrations.
Rails provides a configuration option to indicate if we want to be alerted if any migration is pending.
This will raise an error of the pending migrations and notify the user as shown in the image below.
This can be disabled with the false
value
for the option as shown below.
Migration file name format
There is a convention for naming the migration files.
It uses values from the current time for YYYYMMDDHHMMSS
and the name of the migration.
Once migrations are run, the value YYYYMMDDHHMMSS
in migration file,
is inserted in a table named schema_migrations
.
Pending migration check
Rails provides a method to check if any migration is pending. Listing relevant methods from ActiveRecord::MigrationContext class below.
This piece of code raises an exception ActiveRecord::PendingMigrationError
if any migration is pending.
In the next section, we will see the logic used for needs_migration?
method.
Logic
migrations
method returns versions (YYYYMMDDHHMMSS
) of all the migration files available in the application.get_all_versions
method returns all the versions available inschema_migrations
tablepending_migration_versions
method returns the difference between the two arrays mentioned above.
If there is any file with a version that is not availble in the database needs migration
This is the basis of the logic followed for figuring out if any migration is pending. If you liked reading, please subscribe to the newsletter.
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox