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

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay