donald
donald

Reputation: 23737

Rails 3: Compare unique codes

What's the best way to guarantee that a code is unique? The code is XXX-XXXXX where X is a number only.

What way other than search for the code in a database table there is to make the process faster and cleaner?

Regards.

Upvotes: 0

Views: 686

Answers (3)

Jake Dempsey
Jake Dempsey

Reputation: 6312

A hash based on time is actually not 'guarateed' to be unique. Using some type of hash is just a way to create a digest from a large source data. Since all data can then be described in 128bits (using md5) then its possible to encounter hash collisions.

The validates :uniquness will do a query to determine if the fields value has been used before. You can use this but it should not be your only solution. If the field is intended to be unique, you should place a unique index on the column in the database. If you only rely on the rails validation, you are running the risk of a race condition on data insertion into the table. I can bypass the validation, but another write could have also passed the validation and both end up getting into the table.

Are you generating the value or is it user input?

Upvotes: 0

Heikki
Heikki

Reputation: 15417

  1. Normal approach is to use :uniqueness validation. That handles db searching.
  2. More bulletproof is to use 1) + unique index on that field. If the saving fails without validation errors, you could generate a new code and try again.

Upvotes: 5

sethvargo
sethvargo

Reputation: 26997

Since no two times are the same, using some kind of hash based on time is the easiest way to guarantee uniqueness. If you are storing xxx-xxxx though, you are limiting yourself. You may also use a unique auto-incrementing value. Store the value server-side for the next number to be assigned and then increment it whenever you issue a new unique id.

both are acceptable options without knowing additional information

Upvotes: 0

Related Questions