loading...

5 Rails Migration Patterns to Save the Day

jasterix profile image Jasterix Updated on ・1 min read

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

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

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

Delete the Accounts table from your database

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

Undo your recent changes

  • rails db:rollback

Discussion

pic
Editor guide