I was getting this error when running my tests, but everything seemed OK in development:
PG::ForeignKeyViolation: ERROR: update or delete on table “users” violates foreign key constraint “transactions_user_id_fk” on table “transactions” (ActiveRecord::InvalidForeignKey)
DETAIL: Key (id)=(1) is still referenced from table “transactions”.
: DELETE FROM “users”;
This was related to database permissions and the DatabaseCleaner gem.
DatabaseCleaner wants to disable all referential integrity before and after every test, so that it can quickly delete everything in the database without worrying about foreign keys. A quick
tail -n 50 log/test.log showed that the database user does not have permission to do that, thus the error:
(42.1ms) ALTER TABLE “schema_migrations” DISABLE TRIGGER ALL;ALTER TABLE “delayed_jobs” DISABLE TRIGGER ALL;ALTER TABLE “users” DISABLE TRIGGER ALL;ALTER TABLE “stocks” DISABLE TRIGGER ALL;ALTER TABLE “transactions” DISABLE TRIGGER ALL
PG::InsufficientPrivilege: ERROR: permission denied: “RI_ConstraintTrigger_a_362782” is a system trigger
The (short term) solution was to make the database user a superuser, which seems OK since this is only needed in the test environment, and not in Production. (In production it would be a security vulnerability). I may ask around if this is a good long term solution, or if there is some better way to deal with this.