0
0
Ruby on Railsframework~5 mins

Adding and removing columns in Ruby on Rails

Choose your learning style9 modes available
Introduction

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.

You want to store a new piece of information about users, like their phone number.
You need to remove a column that is no longer needed to keep the database clean.
You want to change the database to support a new feature in your app.
You are fixing a mistake where a column was added by accident.
You want to improve performance by removing unused columns.
Syntax
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.

Examples
This adds an integer column called age to the users table.
Ruby on Rails
class AddAgeToUsers < ActiveRecord::Migration[7.0]
  def change
    add_column :users, :age, :integer
  end
end
This removes the nickname column from the users table.
Ruby on Rails
class RemoveNicknameFromUsers < ActiveRecord::Migration[7.0]
  def change
    remove_column :users, :nickname
  end
end
Sample Program

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.

Ruby on Rails
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
OutputSuccess
Important Notes

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.

Summary

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.