Fixing PGError: ERROR: column of relation already exists
This error happens when you try to run a migration adding a column that already exists.
For instance, let’s say you write a migration in your local environment to add the column
source to a
lead. You run it then realize your migration is useless.
So you delete the migration file but forget to
rails db:rollback 😱. Rookie mistake! Your
source column is still in
schema.rb and in your local database.
If you later pull a colleague’s branch that add a
source column to
leads, you’ll get:
Your database’s schema is corrupted. At this point, you can’t do much to correct your mistake. You could:
- write a migration file to delete your
- meddle with the fingerprinting to have this migration run before your colleague’s
- delete the file once you ran
But that's a lot of messing around with a lot of possibilities to make things worse.
Another - and safer way - is to save your database and restore it anew. Let’s see how to do this:
1) Find the database’s name in
database.yml and run the following command.
This will export your database to a
2) Drop the database and recreate it
3) Restore your data to your database
The schema and database will sync up on your migration files. No more
Don’t forget to delete your
<pick_a_file_name>.psql file from
If you run into the following error:
run this into your terminal:
It’ll identify the server already running and kill it.