5 Rails Migration Patterns to Save the Day

Jasterix - Jul 14 '19 - - Dev Community

Apologies in advance because the formatting for this post is a little funky. The original goal was to have a numbered list, but that's not working out.

However, each migration builds on the previous so I hope it helps you understand the flow of setting up Rails migrations.

Create a new model Users

  • rails g model Users :name :city
class CreateUsers < ActiveRecord::Migration[5.2]
  def change
    create_table :users do |t|
      t.string :name
      t.string :city

      t.timestamps
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

Rename your Users Table to Accounts

  • rails g migration rename_users_to_accounts
class RenameAccountsToTwitterAccounts < ActiveRecord::Migration[5.2]
  def change
    rename_table :users, :accounts
  end
end

Enter fullscreen mode Exit fullscreen mode

Add a new column to your Accounts table

  • rails g migration AddEmailToAccounts email:string
class ChangeAccountsTable < ActiveRecord::Migration[5.0]
  def change
    add_column :accounts, :email, :string
  end
end
Enter fullscreen mode Exit fullscreen mode

Delete the Accounts table from your database

  • rails g migration DropInstalls
class DropAccounts < ActiveRecord::Migration[5.2]
  def change
    drop_table :accounts
  end
end
Enter fullscreen mode Exit fullscreen mode

Undo your recent changes

  • rails db:rollback
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player