Performance: Changing column types
This affects page load speed indirectly by impacting database query performance and server response time, which can delay rendering of data-driven pages.
class ChangeColumnTypeGood < ActiveRecord::Migration[7.0] def up add_column :users, :age_new, :string execute('UPDATE users SET age_new = age::text') remove_column :users, :age rename_column :users, :age_new, :age end def down # reverse steps end end
class ChangeColumnTypeBad < ActiveRecord::Migration[7.0] def change change_column :users, :age, :string end end
| Pattern | Database Locking | Query Speed | User Impact | Verdict |
|---|---|---|---|---|
| Direct change_column | Full table lock | Slow during migration | Page load delays, downtime | [X] Bad |
| Add new column + backfill | Minimal locking | Fast queries after migration | Minimal downtime, faster page loads | [OK] Good |
What is the primary Rails method used to change the type of an existing database column in a migration?
add_column adds new columns, remove_column deletes columns, and rename_column changes column names.change_column is designed to change the type of an existing column without removing it.Which of the following is the correct syntax to change a column named price to type decimal with precision 8 and scale 2 in a Rails migration?
class ChangePriceTypeInProducts < ActiveRecord::Migration[7.0]
def change
?
end
endchange_column(table, column, type, options). Options like precision and scale are passed as keyword arguments.precision: 8, scale: 2 as keyword arguments. change_column :products, :price, :decimal(8,2) uses invalid syntax. change_column :products, :price, :decimal, {precision: 8, scale: 2} uses a hash but without keyword arguments. change_column :products, :price, :decimal, precision => 8, scale => 2 uses hash rockets which is invalid in this context.Given this migration snippet, what will be the new type of the age column after running it?
class ChangeAgeTypeInUsers < ActiveRecord::Migration[7.0]
def change
change_column :users, :age, :string
end
endage column in the users table to type :string.age column will store string values instead of its previous type.What is wrong with this migration code that tries to change a column type?
class ChangeActiveToBooleanInUsers < ActiveRecord::Migration[7.0]
def change
change_column :users, :active, 'boolean'
end
end:boolean, not a string.You want to change a column rating from integer to decimal with precision 3 and scale 1, but keep existing data safe. Which approach is best?
Pass the test and this pattern moves unknown