I was meaning to dig into this further to see if this is a bug or something I was doing wrong/setup, but the “A May of WTFs” was announced so I figured I throw it out there.
- Rails edge
- Postgresql backend, specifically in production
- Using pg gem version 1.2.3
- S3 compatible backend for ActiveStorage store
DraftProject --> has_many_attached :files Project --> has_many_attached :files
Problem: I’ve noticed that sometimes when I’m attaching the blobs from the DraftProject (through files) to the Project model that ActiveRecord::RecordNotUnique is raised. (ie. The blob is already attached to DraftProject, and now I also associate the same blob to Project).
Looking through the logs, it looks like Postgres is returning an error on this index: [“record_type”, “record_id”, “name”, “blob_id”] and throwing a PG::UniqueViolation. When I query ActiveStorage::Attachment with the offending parameters, no records are found (ie. there is actually no unique condition violation).
Right now, I’m getting around this with a rescue block like so:
draft_project.files.each do |file| begin project.files.attach(file.blob) end rescue ActiveRecord::RecordNotUnique, PG::UniqueViolation => e ActiveRecord::Base.connection.reset_pk_sequence!("active_storage_attachments") project.files.attach(file.blob) end end
This seems to be able to fix it. Would appreciate the community’s thoughts on this. Is it a bug in Rails, in Postgres, in the way I’m implementing the code, or something else?
For reference, the database’s product (Postgres) DB is running @ Digital Ocean under their managed DB product.