PG :: UndefinedTable:错误:关系“…”不存在

在迁移时,我收到以下错误消息:

PG::UndefinedTable: ERROR: relation "actioncodes" does not exist : ALTER TABLE "organizations" ADD CONSTRAINT "fk_rails_4ecaa2493e" FOREIGN KEY ("actioncode_id") REFERENCES "actioncodes" ("id") 

我有组织的以下迁移文件:

 class CreateOrganizations < ActiveRecord::Migration def change create_table :organizations do |t| t.string :name, null: false, limit: 40 t.references :actioncode, index: true, foreign_key: true t.boolean :activated t.datetime :activated_at t.timestamps null: false end end end 

对于Actioncodes,我有迁移文件:

 class CreateActioncodes < ActiveRecord::Migration def change create_table :actioncodes do |t| t.string :code, null: false, limit: 20 t.string :description, limit: 255 t.timestamps null: false end end end class AddIndexToActioncodesCode < ActiveRecord::Migration def change add_index :actioncodes, :code, unique: true end end 

组织模型文件包括: belongs_to :actioncode

动作代码模型文件包括: has_many :organizations

知道什么可能导致错误消息?

如果从迁移文件中删除index: true, foreign_key: true ,它将无错误地迁移。 当我用不正确的行t.references :actioncode_id, index: true, foreign_key: true替换该行时,它给出了下面的错误,其中最后一行(“ids”)表明Rails似乎有点名称的问题桌子?

 PG::UndefinedTable: ERROR: relation "actioncode_ids" does not exist : ALTER TABLE "organizations" ADD CONSTRAINT "fk_rails_604f95d1a1" FOREIGN KEY ("actioncode_id_id") REFERENCES "actioncode_ids" ("id") 

因此,问题正在发生,因为在执行CreateActioncodes之前正在运行CreateOrganizations迁移。

首先运行CreateActioncodes ,从而确保存在action codes表。

运行迁移的顺序基于迁移的时间戳 – 如文件名中所示。 20141014183645_create_users.rb将在20141014205756_add_index_to_users_email.rb之前运行,作为第二个的时间戳 – 20141014205756在第一个的时间戳之后 – 20141014183645

确保CreateOrganizations迁移的时间戳记在CreateActioncodes迁移的时间戳之后。

您可以手动更改文件名中的时间戳。 或删除这些迁移文件,并按正确的顺序创建它们。

foreign_key: true这一行是foreign_key: true

 t.references :actioncode, index: true, foreign_key: true 

告诉Rails在数据库中创建一个外键。 外键 :

约束指定列(或一组列)中的值必须与另一个表的某行中出现的值匹配。 我们说这维持了两个相关表之间的引用完整性

因此,它是数据库中的一些逻辑(它所属的位置),可确保您无法在操作actioncode列中放置无效值,并且无法从其他地方使用的actioncodes表中删除条目。

为了创建约束,引用的表( actioncodes )需要在引用之前存在。 看起来您的迁移尝试在actioncodes之前创建organizations ,因此您只需重命名CreateOrganizations迁移文件,使其时间戳前缀位于CreateActioncodes 。 前缀只是格式为YYYYMMDDhhmmss的时间戳,因此将CreateOrganizations时间戳更改为CreateActioncodes时间戳再多一秒。

我也遇到了这个错误。 如果您使用测试数据库运行rspec,请确保在运行rspec之前在终端中运行rake db:test:prepare