Ruby On Rails Migration

Ruby on Rails migrations: an example of how to create, manage, and rollback database schema changes.

Ruby On Rails Migration

Migrations are a convenient way to alter your database schema over time in a consistent and easy way. They use a Ruby DSL (Domain Specific Language) that describes changes to your database. Each migration file has two parts, an up method which is run when you migrate up to a certain version, and a down method which is run when you rollback that version.

Migrations are stored in the db/migrate directory and named using the format YYYYMMDDHHMMSS_create_table_name.rb. Rails will look for migrations in this format and will run them in order.

Here is an example of a migration that creates a posts table with four columns, title, body, created_at, and updated_at:

class CreatePosts < ActiveRecord::Migration
  def up
    create_table :posts do |t|
      t.string :title
      t.text :body
      t.timestamps
    end
  end

  def down
    drop_table :posts
  end
end

The first line of the migration specifies the name of the migration and what class it inherits from. The following up and down methods will be called when the migration is run. In the up method, we use the create_table method to create a new table named posts with four columns.

The down method uses the drop_table method to delete the posts table. After the up and down methods are defined, the migration is complete and ready to be run. Rails will look for migrations in the db/migrate directory and run them in order.

Migrations are a powerful tool that allow you to make changes to your database in a consistent and easy way. They are a great way to keep your database schema in sync with the code that is written against it.

Answers (0)