Manish Kadam
Manish Kadam

Reputation: 11

Rails: how to insert unique value into the database without duplication?

I am new to ruby on rails. i want to generate unique token for each client. i can generate unique token with SecureRandom.hex(6),but then i have to check wheter this value exists in the database and it is very time consuming if the database is very large. i can append the current time to secureadnom.hex(6) function but then again if the rails processes the two request at the same time then there is no guaranty of uniqueness.

Can someone tell me the best way to generate unique token without hitting query to database level.

Thanks,

Upvotes: 0

Views: 404

Answers (2)

Athar
Athar

Reputation: 3268

do this.

#attribute = [SecureRandom.urlsafe_base64, Time.now.to_i].join("")

for your attribute which you want to set. probability will be very less that one value will duplicate it self and to remove that you can add validation on that field.

validates_uniqueness_of :attribute

Upvotes: 1

Nitin Satish Salunke
Nitin Satish Salunke

Reputation: 516

To guarantee that the token generated is unique you can put a unique constraint on your index. And then in your code you can handle the exception.

example

begin
#generate your code here and try to save it.
rescue ActiveRecord::RecordInvalid => e
#If exception occurs then again repeat the same process for another hex code and save it.
end

Upvotes: 1

Related Questions