Rails migrations can do more than you think!
Over the past year I have really started to realise the true power and differences in what you can do in a Rails migration and I wanted to share some of cool tips I have picked up.
Let’s start simple! Renaming columns;
rename_column :my_table, :my_field_old_name, :my_field_new_name
If you have been using Rails for even a short period of time I would assume that most of people would know about this one, simple easy and effective.
This is one I learnt quite recently (I think before I used to `remove_index` and then `add_index`).
rename_index :my_table, 'old_name_of_index', 'new_name_of_index'
As you can see, this works pretty much the same as the `rename_column` migration, which makes it easier to remember.
Changing column default
Now I am not too ashamed to admit this, but for the longest time to change a column default I used to run this migration;
# Say we have a `my_field` column which defaults to false
change_column :my_table, :my_field, :boolean, default: true
I would use the `change_column` and repeat all of the column fields but change the default… but now;
# Again assuming we have a `my_field` column which defaults to false
change_column_default :my_table, :my_field, true
So much nicer!
I’m sure adding indexes is something pretty much everyone knows how to do, but it’s the little extra things which make it powerful.
Changing the algorithm
Were you aware that you could change the way in which the index was applied? For example you have a large table which you want to add an index to. Instead of just using the default option, which will hold a lock on your table while the index is being created, you can choose to create your index concurrently. This is super easy to achieve with Rails migrations;
add_index :my_table, :my_field, algorithm: :concurrently
Your migration will no longer lock your table!
Partial indexes cover a subset of data and can greatly increase efficiency by reducing the size of the index which makes it faster to scan. Again Rails makes it incredibly simple to create a partial index like so;
add_index :my_table, :my_field, where: 'active IS NOT NULL'
I have only covered some of the wonders of what Rails gives us within migrations but hopefully some of it has been new. There is a lot more awesomeness too, all of which can be checked out here: http://api.rubyonrails.org/classes/ActiveRecord/Migration.html