How to Add a Column Using Migration in Ruby on Rails
To add a column in Ruby on Rails, create a migration using
rails generate migration and use add_column :table_name, :column_name, :type inside the migration file. Then run rails db:migrate to apply the change to the database.Syntax
The basic syntax to add a column in a Rails migration is:
add_column :table_name, :column_name, :type- adds a new column to the specified table.:table_name- the name of the existing database table.:column_name- the name of the new column you want to add.:type- the data type of the new column (e.g.,string,integer,boolean).
ruby
class AddColumnNameToTableName < ActiveRecord::Migration[7.0] def change add_column :table_name, :column_name, :type end end
Example
This example adds a birthdate column of type date to the users table. After running the migration, the users table will have a new birthdate column.
ruby
class AddBirthdateToUsers < ActiveRecord::Migration[7.0] def change add_column :users, :birthdate, :date end end
Output
== 20240601000000 AddBirthdateToUsers: migrating ==============================
-- add_column(:users, :birthdate, :date)
-> 0.0012s
== 20240601000000 AddBirthdateToUsers: migrated (0.0013s) =====================
Common Pitfalls
Common mistakes when adding columns include:
- Forgetting to run
rails db:migrateafter creating the migration. - Using the wrong data type for the column.
- Not specifying the correct table name.
- Trying to add a column that already exists, which causes an error.
Always check your migration file and database schema after migration.
ruby
class AddAgeToUsers < ActiveRecord::Migration[7.0] def change # Wrong: misspelled table name add_column :user, :age, :integer # Correct: # add_column :users, :age, :integer end end
Quick Reference
| Command | Description |
|---|---|
| rails generate migration AddColumnNameToTableName | Creates a new migration file to add a column |
| add_column :table_name, :column_name, :type | Adds a new column in the migration file |
| rails db:migrate | Runs the migration to update the database schema |
| rails db:rollback | Reverts the last migration if needed |
Key Takeaways
Use
add_column :table_name, :column_name, :type inside a migration to add a column.Always run
rails db:migrate after creating the migration to apply changes.Double-check table and column names to avoid errors.
Choose the correct data type for your new column.
Use
rails db:rollback to undo migrations if necessary.