chris morgan
chris morgan

Reputation: 61

Ruby generate unique integer for use as a primary key

I need to generate a unique integer that will be assigned to the id field within a rails app. What is the best way of doing this. (using the usual auto increment is not an option and it has to be an integer.)

Upvotes: 6

Views: 7344

Answers (3)

Travis Haby
Travis Haby

Reputation: 150

You could also use securerandom's .random_number() method if you don't want to do the gsub bit:

SecureRandom.random_number(100000000000000000000000000000)

https://www.rubydoc.info/stdlib/securerandom/1.9.3/SecureRandom#random_number-class_method

Upvotes: 2

Kimmo Lehto
Kimmo Lehto

Reputation: 6041

Ruby 1.9 has UUID version 4 generation included in module SecureRandom:

> require 'securerandom'
 => true
> SecureRandom.uuid
 => "4b3a56db-4906-4a44-a262-975d80c88195" 
> SecureRandom.uuid.gsub("-", "").hex
 => 56667719780883163491780810954791777167

A bit lengthy, but unique for sure.

Upvotes: 24

thomasfl
thomasfl

Reputation: 159

I don't understand why you can't use auto increment, but have you considered using a random number?

id = rand(1000000)
while(Post.find(id) != nil)
  id = rand(1000000)
end

Upvotes: -2

Related Questions