0
0
Ruby on Railsframework~5 mins

Database folder and migrations in Ruby on Rails

Choose your learning style9 modes available
Introduction

The database folder in Rails keeps all files related to your app's data. Migrations help you change the database structure safely over time.

When you want to create a new table to store data like users or products.
When you need to add or remove columns from an existing table.
When you want to rename or change the type of a column in your database.
When you want to keep track of changes to your database structure in a clear, organized way.
When you need to share database changes with your team or deploy them to a server.
Syntax
Ruby on Rails
rails generate migration MigrationName

# Inside the generated migration file:
class MigrationName < ActiveRecord::Migration[7.0]
  def change
    create_table :table_name do |t|
      t.string :column_name
      t.timestamps
    end
  end
end

Migration files live in the db/migrate folder.

The change method describes what changes to make to the database.

Examples
This creates a new users table with name, email, and timestamp columns.
Ruby on Rails
rails generate migration CreateUsers

# Migration file example:
class CreateUsers < ActiveRecord::Migration[7.0]
  def change
    create_table :users do |t|
      t.string :name
      t.string :email
      t.timestamps
    end
  end
end
This adds an age column of type integer to the existing users table.
Ruby on Rails
rails generate migration AddAgeToUsers age:integer

# Migration file example:
class AddAgeToUsers < ActiveRecord::Migration[7.0]
  def change
    add_column :users, :age, :integer
  end
end
This removes the email column from the users table.
Ruby on Rails
rails generate migration RemoveEmailFromUsers

# Migration file example:
class RemoveEmailFromUsers < ActiveRecord::Migration[7.0]
  def change
    remove_column :users, :email, :string
  end
end
Sample Program

This example shows how to create a migration to add a books table with title and author columns. Running rails db:migrate applies the change to the database.

Ruby on Rails
# Terminal command to create migration
rails generate migration CreateBooks title:string author:string

# db/migrate/20240601000000_create_books.rb
class CreateBooks < ActiveRecord::Migration[7.0]
  def change
    create_table :books do |t|
      t.string :title
      t.string :author
      t.timestamps
    end
  end
end

# After creating migration, run:
rails db:migrate

# This creates the books table with title, author, and timestamps.
OutputSuccess
Important Notes

Always write clear migration names to understand what changes they make.

Run rails db:migrate to apply migrations to your database.

You can rollback migrations with rails db:rollback if needed.

Summary

The db folder holds your database setup and migrations.

Migrations let you change your database structure step-by-step.

Use migrations to create, update, or delete tables and columns safely.