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!
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With