DEV Community

Jasterix
Jasterix

Posted on • Edited on

1 1

5 Rails Migration Patterns to Save the Day

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more