Hello Rails community,
I’d like to propose a small enhancement to ActiveRecord’s uniqueness
validation: when validation fails because a value is already taken, include the primary key (id) of the existing record in errors.details
in addition to the conflicting value.
Rationale:
-
It makes error handling in APIs and UIs more precise — clients can reference the exact existing resource instead of only knowing the duplicate value.
-
It helps debugging (quickly point to the conflicting row).
Two example shapes for the extra metadata:
Option A — use id
as an extra key inside the details hash:
record.valid?
record.errors.details
# => { field: [{ error: :taken, value: 'duplicate_value', id: 1 }] }
Option B — explicitly name the primary key in the details:
record.valid?
record.errors.details
# => { field: [{ error: :taken, value: 'duplicate_value', primary_key: 1 }] }
Implementation considerations:
- It should not change the semantics of uniqueness validation itself — only the metadata attached to
errors.details
.
I believe this small change would be valuable for API authors and client apps. If the core team and community find this useful, I’m happy to prepare a prototype and open a pull request implementing the behavior (with tests and an opt-in flag).
Thanks for reading — curious to hear thoughts and potential pitfalls I might have missed.