tommyd456
tommyd456

Reputation: 10673

Generate a unique code in method

I've watched a lot of Railscasts (thanks Ryan) and I need to recall some code I saw in one of them but my problem is I can't remember where to find it.

I can generate a 5 digit code using the code below and this is found in a method:

5.times.map { [*'A'..'Z'].sample }.join

but I need to be able to make sure that it's unique before saving. I remember Ryan using a loop of some sort in the model method to check that it is unique before saving.

Can you help?

Upvotes: 0

Views: 567

Answers (2)

Dylan Markow
Dylan Markow

Reputation: 124419

http://railscasts.com/episodes/274-remember-me-reset-password is the page you're looking for:

def generate_token(column)
  begin
    self[column] = SecureRandom.urlsafe_base64
  end while User.exists?(column => self[column])
end

So you could replace the SecureRandom.urlsafe_base64 part with your own code.

Upvotes: 2

apneadiving
apneadiving

Reputation: 115511

first, replace your stuff with: SecureRandom.hex(5)

Then I get what you're looking for, something like this I bet:

value   = true
while value
  random = SecureRandom.hex(5)
  value  = Model.where(column: random).exists?
end
#here you have an unique `random`

Upvotes: 1

Related Questions