How to change your model scheme through migrations in Active Record

Create a migration

If you have rake installed, you can enter in the terminal: rake db: create_migration NAME=name of the migration typically named create_tablename.

Next you worry about creating the table in your migration.

The change method is automatically created and you use create_table to create your table. Other options include add_column or remove_column. Next you want to name your migration to fit your Model.

Note: In the migration, you want to name the table the plural form of the Model. Ex) Recipes vs Recipe (for the model).

Next you add your columns starting with do |t| then t.type for strings, you use t.string, t.integer for integers etc. after that, you choose the column name.

Finally you want to run the migration. In the terminal, run the command: rake db:migrate

That’s how you make a table! Let’s talk about editing your table to remove or add additional columns.

Note: You do not make changes to your first migration when editing. You will need to create a new migration.

Create a new migration and name it something descriptive: Add_column_to_tablename or Remove_columns_from_tablename

Now that you created the migration using rake, you can start to make your adjustments.

You can remove a column by remove_column :nameoftable, :nameofcolumnremoving, :columntype.

If you need to remove more than one column, you can just add another row starting with remove_column again.

Adding a column is very similar. Follow the steps above, but use add_column instead of remove_column.

You can view your updated schema in the schema.rb file

The New Guy!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store