在执行rake迁移过程中,关系已经存在

12

我已经将博客引擎安装到了refinerycms中,目前运行得很完美。

现在我生成了一个带有一些表格字段更改的迁移(当然不是refinerycms或博客表),但是出现了错误:

== 创建博客结构: 进行迁移 ============================================
-- create_table("refinery_blog_posts", {:id=>true})
注意:CREATE TABLE将为序列“refinery_blog_posts_id_seq1”创建隐式序列以进行自动增长的主键"refinery_blog_posts.id"
rake终止!
发生错误,此次和之后所有迁移均已取消:

PG::Error: 错误: 关系 "refinery_blog_posts" 已经存在
: 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)

任务: TOP => db:migrate
(使用--trace选项运行任务以查看完整跟踪信息)

3个回答

17

检查您的db/schema.rb

很可能在那里创建了与db/migrate/[timestamp]your_migration中迁移相同的表格。

如果db/migrate/[timestamp]your_migration是架构中已经存在的重复内容,则可以将其删除,程序应该就能够正常运行。


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

Pg是一个Rails gem,它允许Rails与PostgreSQL之间进行通信。它将您的迁移关联到SQL表格,因此会出现关系错误。因此,错误信息的意思是:

我正在尝试创建基于迁移X的表格X,但是表格X已经存在于数据库中。

可能的解决方案:

  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.


1
重要提示:迁移是由ActiveRecord gem添加的,而不是pg gem。 - Chris Hall

0

由于这是一个明显但容易忽视的错误原因(并且这是搜索引擎带来的第一篇文章),因此需要添加。

如果您在同一次迁移中意外定义了相同的关系,则会出现此错误。

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

看起来很明显,但很容易忽略。要修复它,只需删除重复的引用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接