Search code examples
ruby-on-railsdatabaseforeign-keyspsqlcomposite-primary-key

Why Composite Primary Key is not added as a Foreign Key in psql (rails app)?


I am using activerecord-multi-tenant gem for implementing MultiTenancy in my rails project.

Followed instruction from here

I have a User model, Attendance Model which belongs to User, And Company as a tenant.

While I am updating User's primary key(id) to composite key(id, company_id) It is updating.

But when I am trying to update the Foreign key in Attendance models it is only trying to take user_id as a fk and searching for its unique constraint.

Here is the commands i used -

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);'

The Error i am getting while 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")


Solution

  • The solution was using structure.sql file. In schema.rb file it cant always follow the sql command and reflect in the database. So I was getting this error InvalidForeignKey as schema couldn't load the sql command properly.

    After moving to structure.sql all the migration were run properly with exact commands inside the files.