Rails DB Migration Error: Relationship Already Exists

I get an error when trying to transfer my db. I don’t quite remember how I got here, but I believe that I:

  • created a new branch, scaffolding "Requests", db: moved, switched back to the master and merged branch
  • created another branch, did something, db: migrated, and everything worked fine.
  • pulled heroku from the postgres database so i can check if the actual data worked. then tried db migrating but gave me this error:

    rake db:migrate == CreateRequests: migrating ================================================= -- create_table(:requests) NOTICE: CREATE TABLE will create implicit sequence "requests_id_seq1" for serial column "requests.id" rake aborted! An error has occurred, this and all later migrations canceled: PG::Error: ERROR: relation "requests" already exists : CREATE TABLE "requests" ("id" serial primary key, "title" character varying(255), "content" text, "category" character varying(255), "status" character varying(255), "requested_track_id" integer, "created_at" timestamp, "updated_at" timestamp) 

Any ideas?

+6
source share
2 answers

I'm not sure exactly which strategy you used, but if we make two reasonable assumptions about your pull strategy:

  • it does not drop the database, but simply overwrites the tables, as this requires less permissions.
  • it works in a kind of "archive mode", that is, it does not drop tables at the destination just because they do not exist in the source. Think rsync; you must specify --delete to find out what might be your expected behavior with this utility.

If your steps are correct, then what happened, you rewrote the schema_migrations table, so Rails believes that you have not added the table yet, but your hero did not pull out the table because of number 2 above.

Do not create a new migration. . This will not work on all elses computers except yours, but will only work once.

Instead, run rails dbconsole and do something like DROP TABLE 'requests' (I forgot postgres syntax, maybe not so). Then you can complete your migrations.

+4
source

There is another way to avoid deleting a table with data in it.

What I do in these cases is to check which migration fails.

Suppose you have a db/migrate/20130908214222_create_requests.rb , and for some reason ActiveRecord failed in the past when it saved this migration in its tracking system.

To verify that this is the case, simply look in the schema_migrations table schema_migrations row containing a number similar to this example: 20130908214222

If this line does not exist, you just need to insert a new one:

 INSERT INTO schema_migrations( version ) VALUES ( 20130908214222 ); 

The next time you run rake db:migrate , ActiveRecord will skip this step and continue the migration to the end without complications.

+2
source

All Articles