Introduction

I assume you have already read my previous article on Page linking and URL parameters In Ruby on Rails. Now, you will learn to how to create Migration files, migration models creation, what migration is, why you should use migration and how to run migration files in Ruby on Rails.

Requirements

What is migration?

Why use migrations?

Generate migrations

  • Now put following rails code in command prompt.
  1. Rails generate migration record1
  • The migration file converted in camel Case to underscore: record_1.rb. And then it puts the current date and time as time stamp in front of it.
  • The migration file is located in db directory, inside migrate, and that file has Ruby class defined in it. You can see our file name record there. It inherits from active record migration. That class is called one method.

Default method code for migration

  1. class CreateUsers < ActiveRecord::Migration[5.1]
  2. def change
  3. end



Now we separate that method into two up and down methods. Rails is going to execute the code that is inside our up or down methods. Up will describe the changes we want to make to the current database. Down will describe how to reverse those database changes.

Create two methods using the following code,

  1. class CreateUsers < ActiveRecord::Migration[5.1]
  2. def up
  3. end
  4. def down
  5. end
  6. end

Generate Migration Models

Now, we create model for migration. The way of creating model by using the rails generates command in rails command prompt. Put the following rails code.
  1. Rails generate model user


The model file is located in db directory, inside migrate folder. Put that model file in the following code,
  1. class CreateUsers < ActiveRecord::Migration[5.1]
  2. def up
  3. create_table: users do |t | t.column "first_name", : string, : limit => 25
  4. t.string "last_name", : limit => 50
  5. t, string "email", : default => '', : null => false
  6. t.string "password", : limit => 40
  7. t.timestamps
  8. end
  9. def down
  10. drop_table: users
  11. end
  12. end
  13. end


Above the code you can see that names created users. It also inherits from active record migration. The up method code will create table and down method code deletes the created table in database.

Run a migration

  1. Rails db:migrate



Now, we successfully ran migration file in rails command prompt.

Conclusion

I hope you understood how to create Migration files and migration models creation, what migration is, why we should use migration and how to run migration file in Ruby on Rails. In future articles you will learn more Ruby on Rails in a step by step easy to learn way. Keep in touch.