Ruby on Rails Rails generate commands Rails Generate Migration


You can generate a rails migration file from the terminal using the following command:

rails generate migration NAME [field[:type][:index] field[:type][:index]] [options]

For a list of all the options supported by the command, you could run the command without any arguments as in rails generate migration.

For example, if you want to add first_name and last_name fields to users table, you can do:

rails generate migration AddNamesToUsers last_name:string first_name:string

Rails will create the following migration file:

class AddNamesToUsers < ActiveRecord::Migration[5.0]
  def change
    add_column :users, :last_name, :string
    add_column :users, :first_name, :string

Now, apply the pending migrations to the database by running the following in the terminal:

rake db:migrate
rails db:migrate

Note: For even less typing, you can replace generate with g.