Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rake task to list all migrations for a given model

On the terminal, is there a rake task to list all the migrations which have been run on a particular model? If not, how do I go about building one?

When I ran rake -T, rake db:migrate:status seemed to be the right answer, but it gave me Migration Name as one of the columns. And though the name Add logo to company does indicate Company model, not all migrations have such explicit names. Case in point being Change data type for content. I have 400 odd migration files, so this feature would be really helpful.

So, the ideal output would be:

database: abcd_development

 Status   Migration ID    Migration Name     Model Name
----------------------------------------------------------

Thanks!

like image 317
WinkyCharlie Avatar asked Sep 12 '13 11:09

WinkyCharlie


People also ask

What is the difference between rails db Migrate and rake db migrate?

What happens internally is that when rails db:migrate command is executed, Rails checks if db:migrate is something that rails natively supports or not. In this case db:migrate is not natively supported by rails, so Rails delegates the execution to Rake via Rake Proxy.

How does rails keep track of migrations?

Rails stores the most recent database schema in the file db/schema. rb . This file is the Ruby representation of all the migrations run on your database over the life of the application. Because of this file, we don't need to keep old migrations files in the codebase.

What does rake db Reset do?

db:reset: Resets your database using your migrations for the current environment. It does this by running the db:drop , db:create , db:migrate tasks. db:rollback: Rolls the schema back to the previous version, undoing the migration that you just ran.


1 Answers

If you've been sticking with the migration naming conventions, you could just pass the output of rake db:migrate:status through grep:

rake db:migrate:status | grep 'compan'

This isn't perfect, though - migration names aren't required to have anything to do with what they actually do - a migration might add the column 'name' to the 'companies' table and be named EvacuateWeaselTubes and still run just fine.

If you wanted to build a task that could overcome this problem, it would have to parse each of the migration files to see what it changed. Since there's many ways to specify a change in a migration (add_column, a create_table block, or calling execute('CREATE whatever'), for instance), you'd probably want to search for mentions of Model.table_name, then check the schema_migrations table to see if it had been run.

like image 181
MrTheWalrus Avatar answered Sep 29 '22 09:09

MrTheWalrus