Better Rails SQL Migrations
Some people on our team, including me, write raw SQL in Ruby on Rails migrations. But they can get unwieldy when iterating on a complex migration that does multiple things.
Mitigate this is to break up your statements into separate HERDOCs, like so:
def up
execute <<-SQL
update pixaxes set metal = 'diamond' where metal = 'iron';
-- many things...
SQL
execute <<-SQL
update swords set metal = 'diamond' where metal = 'iron';
-- many more things...
SQL
end
If the migration fails, we'll get an error pointing to the specific problematic HEREDOC, instead of essentially 'the entire statement is invalid'. You then put a debugger between any HEREDOC to iterate on the issue.
h/t Jack Christensen
Tweet