【发布时间】:2015-07-29 04:38:03
【问题描述】:
在迁移时,我收到以下错误消息:
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。
而 actioncodes 模型文件包括: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")
【问题讨论】:
-
表名是actioncodes。我已将其迁移文件添加到原始帖子中
-
看起来
CreateOrganizations迁移在执行CreateActioncodes之前正在运行。 -CreateActioncodes将首先运行,从而确保actioncodes表存在。 -
你能否建议我应该如何改变这个?我检查了一下,SQL 代码确实确认在 Actioncodes 之前创建了 Organizations。
-
我认为我需要一个额外的/新的迁移文件来创建引用:
t.references :actioncode, index: true, foreign_key: true。然后从当前组织迁移文件中手动删除该行。但是创建附加/新迁移文件的命令是什么?
标签: ruby-on-rails postgresql ruby-on-rails-4 rails-migrations