Adding and removing columns lets you change the structure of your database tables. This helps you store new types of information or clean up old data.
Adding and removing columns in Ruby on Rails
class AddColumnNameToTableName < ActiveRecord::Migration[7.0] def change add_column :table_name, :column_name, :data_type end end class RemoveColumnNameFromTableName < ActiveRecord::Migration[7.0] def change remove_column :table_name, :column_name end end
Replace table_name with your table's name, and column_name with the column you want to add or remove.
Specify the data_type like :string, :integer, or :boolean when adding columns.
When removing columns, you do not need to specify the data_type.
age to the users table.class AddAgeToUsers < ActiveRecord::Migration[7.0] def change add_column :users, :age, :integer end end
nickname column from the users table.class RemoveNicknameFromUsers < ActiveRecord::Migration[7.0] def change remove_column :users, :nickname end end
This example shows two migrations. The first adds an email column to the customers table. The second removes it. You run these migrations with rails db:migrate to update your database.
class AddEmailToCustomers < ActiveRecord::Migration[7.0] def change add_column :customers, :email, :string end end class RemoveEmailFromCustomers < ActiveRecord::Migration[7.0] def change remove_column :customers, :email end end
Always back up your database before removing columns to avoid losing important data.
Use rails db:rollback to undo the last migration if needed.
Adding columns with default values or not-null constraints may require extra steps.
Adding columns lets you store new data in your tables.
Removing columns cleans up unused data and keeps your database tidy.
Migrations are the safe way to change your database structure step-by-step.