30 May

Modify database schema with migrations - Rails Tricks Issue 9


Hi, this week, I will show you a few useful methods to modify your database schema with Active Record migrations.


You probably found yourself in a situation when a NOT NULL constraint needs to be removed or added to a table. Active Record provides a useful migration method to do so. To add a constraint, you can use:

change_column_null :table, :column, true

To remove it, you can use:

change_column_null :table, :column, false

If you also want to change the default value of the column in one go, you can pass the default value as the last parameter:

change_column_null :table, :column, false, 0

If you want to change the default value only(without changing the NULL constraint), use:

change_column_default :table, :column, "default value"

To have no default value, you need to change it to nil. If you want your migration to be reversible, you can specify a from and to value:

change_column_default :table, :column, from: nil, to: 0


It is rare in my experience, but you can also add or change comments on the database tables or columns. The methods for those are change_column_comments and change_table_comments. Just as when changing the default value, you can change the comment by specifying a new one:

change_column_comment :table, :column, "comment"

Or if you want the migration to be reversible, you can specify the from and to options:

change_column_comment :table, :column, from: "old comment", to: "new_comment"

I know this issue is pretty short, but good stuff comes in small quantities.