3

Getting the below error with associated (belongs_to) models:

PG::ForeignKeyViolation: ERROR: insert or update on table "employees" violates foreign key constraint "fk_rails_0d62068e18" DETAIL: Key (contract_type_id)=(2) is not present in table "contract_types". : INSERT INTO "employees" ("title_id", "surname", "othernames", "department_id", "job_title_id", "gender_id", "date_of_birth", "contract_type_id", "employee_status_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) RETURNING "id"

In this case, contract_type_id is a foreign_key to an excluded model (ContractType)

The error is reported to have come from this line:

@connection.exec_prepared(stmt_key, type_casted_binds.map { |_, val| val })

I am using postgres with the config.use_schemas = true option.

MrYoshiji
  • 54,334
  • 13
  • 124
  • 117
Stephen Baidu
  • 31
  • 1
  • 4
  • 1
    Do you have a ContractType with an id equal to `2`? It seems that your SQL query is trying to create a relationship between an Employee and a non-existing ContractType (try `ContractType.find(2)` in your console to check if the record exists) – MrYoshiji Apr 06 '15 at 20:23
  • Yeah, I have a record with that id but that model is part of the excluded ones. – Stephen Baidu Apr 06 '15 at 21:09

1 Answers1

3

If I understand your model relationships correctly, this may help readers understand the problem. The short: Apartment does not support foreign key constraints between non-excluded models to excluded models.

niborg
  • 390
  • 4
  • 16