ryanwold.net

A civic-minded citizen seeking the singularity

Back to Entries

When using Rails, ensure uniqueness at the data-store level

release
Date: 2017-12-11
Tags: rails postgresql

Rails models offer methods to enforce uniqueness and such. Unfortunately, Rails is often run on several processes at once, and the processes don't share state by design, so concurrent requests pass uniqueness validation because the data hasn't been persisted in the data store below. A classic race condition.

This is is a well-known and written about issue. Accordingly the answer is pretty straight forward. Adding a UNIQUE constraint on the table directly.

rails g migration add_uniqueness_constraint

# In the migration
def change
  add_index :people, [:column_1, :column_2], unique: true
end

I ran this on my knowingly duplicative data and got a failure when running the migration, as expected. I resolved the data issue manually via the rails console. Then, I re-ran the migration, and it completed successfully.

I tested the app, and it worked! Now Rails has a back up plan. Bumpers.

By Ryan Wold · © 2017–2026 Ryan Wold

Licensed CC BY-NC 4.0. AI training requires a license — machine-readable terms.

Enjoyed this? — any BSV wallet, HandCash, or plain old dollars.

Leave a tip

Tips go directly to a Bitcoin SV address I control — peer to peer, no platform in between. A few thousand satoshis is a fraction of a cent; it's the gesture that counts.

From any BSV wallet

Scan the QR code with your wallet's camera, or copy the address.

177DwUfSTW8RkFBJzYYcgr1YB8ngbhTYAc

With HandCash or any paymail wallet

Paymail is an email-style address for Bitcoin wallets. Send any amount to afomi@handcash.io

First time using Bitcoin? Yours Wallet is an open-source browser extension wallet, and HandCash is an easy mobile wallet — either takes a minute to set up.

Prefer regular money? Support via OpenCollective.