Rails Migrations


Create a Migration

Say we have a column in our users table that we are no longer needing, we can generate a migration and add any needed information afterwards.

rails g migration RemovePhoneNumberFromUsers phone_number:string

Rename a Column

rails g migration RenamePhoneNumberFromUsers

Polymorphic Associations

rails g migration AddCommentableToComments body:text commentable:references{polymorphic}

Foreign Keys

rails g migration AddUserToPosts user:references

Adding Decimal Type

rails g migration AddPriceToPosts price:decimal{10-2}

Change the Migration

After running the above code, it will generate a migration which we can find in our migrations folder.

# db/migrations
class RemovePhoneNumberFromUsers < ActiveRecord::Migration[5.0]
  def change
    # Removing the column
    remove_column :users, :phone_number, :string
  end
end

class RenamePhoneNumberFromUsers < ActiveRecord::Migration[5.0]
  def change
    # Renaming the column
    rename_column :users, :phone_numbers, :phones
  end
end

class MyChangeMigration < ActiveRecord::Migration[5.0]
  def change
    change_column :table, :column, :type, :limit => 55
  end
end

class MyChangeMigration < ActiveRecord::Migration[5.0]
  def change
    drop_table :table
  end
end

Run the Migration

If everything looks right in the above above, we can then run our migration.

rails db:migrate