为什么在psql(rails应用程序)中没有将复合主键添加为外键



我正在使用activerecord-multi-tenantgem在我的rails项目中实现MultiTenancy。

遵循此处的指示

我有一个User模型,属于UserAttendance模型,以及作为租户的Company

当我将用户的primary key(id)更新为composite key(id, company_id)时,它正在更新。

但当我试图更新Attendance模型中的外键时,它只是试图将user_id作为fk并搜索其唯一约束。

这是我使用的命令-

execute 'ALTER TABLE users DROP CONSTRAINT users_pkey;'
execute 'ALTER TABLE users ADD CONSTRAINT users_pkey PRIMARY KEY(id, company_id);'
execute 'ALTER TABLE attendances DROP CONSTRAINT attendances_pkey;'
execute 'ALTER TABLE attendances ADD CONSTRAINT attendances_pkey PRIMARY KEY (id, company_id);'
execute 'ALTER TABLE attendances ADD FOREIGN KEY(user_id, company_id) REFERENCES users(id, company_id);'

schema:load时出现的错误

ActiveRecord::StatementInvalid: PG::InvalidForeignKey: ERROR:  there is no unique constraint matching given keys for referenced table "users"
: ALTER TABLE "attendances" ADD CONSTRAINT "attendances_user_id_company_id_fkey"
FOREIGN KEY ("user_id")
REFERENCES "users" ("id")

解决方案使用structure.sql文件。在schema.rb文件中,它不能总是遵循sql命令并反映在数据库中。所以我得到了这个错误InvalidForeignKey,因为架构无法正确加载sql命令。

在转移到structure.sql之后,所有迁移都通过文件中的精确命令正确运行。

最新更新