Nic*_*ick 7 postgresql ruby-on-rails rails-migrations ruby-on-rails-4
在迁移时,我收到以下错误消息:
PG::UndefinedTable: ERROR: relation "actioncodes" does not exist
: ALTER TABLE "organizations" ADD CONSTRAINT "fk_rails_4ecaa2493e"
FOREIGN KEY ("actioncode_id")
REFERENCES "actioncodes" ("id")
Run Code Online (Sandbox Code Playgroud)
我有以下组织的迁移文件:
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
Run Code Online (Sandbox Code Playgroud)
对于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
Run Code Online (Sandbox Code Playgroud)
组织模型文件包括: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")
Run Code Online (Sandbox Code Playgroud)
Pra*_*thy 15
所以问题正在发生,因为CreateOrganizations在执行之前正在运行迁移CreateActioncodes.
CreateActioncodes将首先运行,从而确保action codes表存在.
运行迁移的顺序基于迁移的时间戳 - 如文件名中所示.20141014183645_create_users.rb将在之前运行,20141014205756_add_index_to_users_email.rb因为第二个的时间戳 - 在第一个的时间戳20141014205756之后 - 20141014183645.
确保CreateOrganizations迁移的时间戳在迁移之后CreateActioncodes.
您可以手动更改文件名中的时间戳.或删除这些迁移文件,并按正确的顺序创建它们.
mu *_*ort 10
在foreign_key: true这行:
t.references :actioncode, index: true, foreign_key: true
Run Code Online (Sandbox Code Playgroud)
告诉Rails在数据库中创建一个外键.一个外键:
约束指定列(或一组列)中的值必须与另一个表的某行中出现的值匹配.我们说这维持了两个相关表之间的引用完整性.
因此,它是数据库中的一些逻辑(它所属的位置),它确保您不能在actioncode列中放入无效值,并且无法从actioncodes表中删除其他地方使用的表.
为了创建约束,引用的table(actioncodes)需要在引用之前存在.看起来您的迁移organizations之前正在尝试创建,actioncodes因此您需要做的就是重命名CreateOrganizations迁移文件,使其时间戳前缀位于for之后CreateActioncodes.前缀只是格式为YYYYMMDDhhmmss的CreateOrganizations时间戳,因此将时间戳更改为时间戳再CreateActioncodes增加一秒.
| 归档时间: |
|
| 查看次数: |
15528 次 |
| 最近记录: |