Proposal: include existing record ID in uniqueness validation error details

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.

1 Like

Maybe un option to enable this…

I think this is a useful little enhancement, and it shouldn’t break any existing code.

I prefer the hash key name in Option B: existing_id.If the validation fails during an update, it wouldn’t be obvious whether id refers to the record that already includes the unique value or the record that was being updated.

In terms of getting something like this upstream:

You’d need to include a consumer of the value in your change. I don’t imagine adding an additional value that is not immediately used/consumed immediately by anything else in Rails would be accepted.

I think making the PR would expose the challenges to this, which is possibly a de-optimization of the uniqueness query. But do it!