Vaibhav Rajput
Vaibhav Rajput

Reputation: 189

Relation already exists during rake migration

I have installed a blog engine to refinerycms which is working perfectly.

Now I have generated a migration with some table fields changes (of course not refinerycms or blog tables), but I'm getting an error:

== CreateBlogStructure: migrating ============================================
-- create_table("refinery_blog_posts", {:id=>true})
NOTICE: CREATE TABLE will create implicit sequence "refinery_blog_posts_id_seq1" for serial column "refinery_blog_posts.id"
rake aborted!
An error has occurred, this and all later migrations canceled:

PG::Error: ERROR: relation "refinery_blog_posts" already exists
: CREATE TABLE "refinery_blog_posts" ("id" serial primary key, "title" character varying(255), "body" text, "draft" boolean, "published_at" timestamp, "created_at" timestamp NOT NULL, "updated_at" timestamp NOT NULL)

Tasks: TOP => db:migrate
(See full trace by running task with --trace)

Upvotes: 12

Views: 24789

Answers (3)

Matt H
Matt H

Reputation: 740

Adding as this is an obvious but easy to overlook cause of this error (and this is the first post search engines bring up).

If you accidentally defined the same relationship twice in the same migration this is the error that shows up.

def change
  create_table :books do |t|
    t.belongs_to :author
    t.belongs_to :author # Duplicated column definition
  end
end

Seems obvious but easy to overlook. To fix just remove the duplicated reference.

Upvotes: 1

givanse
givanse

Reputation: 14953

PG::Error: ERROR: relation “refinery_blog_posts” already exists

Pg is a Rails gem, the piece of code that allows communication between Rails and PostgreSQL. It relates your migrations to SQL tables, thus a relation error. So, what the error is saying is:

I'm trying to create table X, based on migration X, but table X already exists in the database.

Possible solutions:

  1. Create migrations that drop those, probably old, tables.
  2. Change the migration's name.
  3. Login to PostgreSQL and drop the table. Something like:

    $ psql -U username databasename
    

    then

    database_name=# drop table table-name;
    

    The exact commands might be a little different though.

Upvotes: 8

Sam Ruberti
Sam Ruberti

Reputation: 1569

Check your db/schema.rb

You most likely have the same table being created there in addition to a migration in db/migrate/[timestamp]your_migration

You can delete the db/migrate/[timestamp]your_migration if it is a duplicate of the one found in the schema and it should work.

Upvotes: 17

Related Questions