How to create migration Ruby on Rails

Learn how to create a Ruby on Rails migration with an example.

Creating a Migration in Ruby on Rails

Creating a migration in Ruby on Rails is essential for making changes to your database. Migrations allow you to create, modify, or delete database tables and columns. They are also used to set up initial data for your application. In this article, we’ll discuss the basics of creating a migration in Ruby on Rails.

First, you need to create a new migration file using the rails generate migration command. This command will create a file that looks like this:

class CreateMyTable < ActiveRecord::Migration
  def change
  end
end

This file is the skeleton of the migration that you will create. Inside of the change method is where you will define the changes you want to make to your database. For example, if you want to create a table called ‘my_table’ with two columns, ‘name’ and ‘age’, you would write the following code:

class CreateMyTable < ActiveRecord::Migration
  def change
    create_table :my_table do |t|
      t.string :name
      t.integer :age
    end
  end
end

This code will create a new table called ‘my_table’ with two columns, ‘name’ and ‘age’. Once you’ve added the code for your migration, you can run the rake db:migrate command to apply your changes to the database.

You can also use migrations to modify existing tables. For example, if you want to add a new column to the ‘my_table’ table, you could use the following code:

class AddGenderColumnToMyTable < ActiveRecord::Migration
  def change
    add_column :my_table, :gender, :string
  end
end

This code will add a new column called ‘gender’ to the ‘my_table’ table. Once you’ve added the code for your migration, you can run the rake db:migrate command to apply your changes to the database.

Finally, you can also use migrations to delete existing tables or columns. For example, if you want to delete the ‘my_table’ table, you could use the following code:

class DropMyTable < ActiveRecord::Migration
  def change
    drop_table :my_table
  end
end

This code will delete the ‘my_table’ table from the database. Once you’ve added the code for your migration, you can run the rake db:migrate command to apply your changes to the database.

In summary, creating a migration in Ruby on Rails is an essential part of making changes to your database. Migrations allow you to create, modify, or delete database tables and columns. You can use the rails generate migration command to create a new migration file, and then use the rake db:migrate command to apply your changes to the database.

Answers (0)