rails aborted! ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR: update or delete on table "users" violates foreign key constraint "fk_rails_03de2dc08c" on table "comments" DETAIL: Key (id)=(11) is still referenced from table "comments". : DELETE FROM "users" WHERE "users"."id" = $1
sambukhari04 opened this issue · 2 comments
I am stuck on this error for a while and have no idea what's wrong. Please HELP!
@sambukhari04 it sounds like you're deleting a record from users
when there is still corresponding data in the comments
table ... the major selling point of foreign keys is that they prevent you from doing that sort of thing, which would otherwise leave orphaned data around. So in this case, the foreign key has caught a problem in your application logic.
To solve this, you probably want to modify your has_many :comments
association in your User
model to have a dependent
option. Some possibilities:
has_many :comments, dependent: :delete_all
- just automatically delete them when the user is deletedhas_many :comments, dependent: :destroy
- like above, but call#destroy
on each comment instead of just deleting directly in the dbhas_many :comments, dependent: :nullify
- don't delete comments when the user is deleted, just null out their user_id column
See http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many for more information
Thanks @jenseng