How to write SQL in a migration in Rails
⚡TLDR
Implement raw SQL in your Rails migration using the execute
method:
Remember:
- The
change
method handles both up and down migrations—Rails can intuit how to reverse it. - For clarity, use a single-line string for short SQL statements.
Advanced scenarios: executing raw SQL
An SQL migration isn't restricted to the execute
method. Based on the complexity and requirements, there are different approaches.
Table renaming and data transformation
When a simple table rename doesn't cut the mustard, and you need to perform some data wizardry:
Reversible changes with style
Rails 4+ introduced reversible
blocks, a swanky way to handle both up
and down
methods in one go:
Elegance with multi-statement SQL
Long live here-docs! They enhance readability of complex multi-step SQL statements:
Mastering migrations: versatility is key
Crafting reversible changes
Write migrations where you manipulate the database schema using SQL? It's crucial you know how to construct reversible changes:
Data safety vs. structural changes
When you meddle with table structures, consider the potential impact on your precious data:
Linked
Was this article helpful?