1

Instead of just seeings my posts page as /posts/1 and so on, I'd prefer to have a random string thats more something like this /posts/299432. I did some research and found this answer on S.O.

How to make model IDs in Rails unpredictable and random

It does work, but I don't think it created a unique ID for the post, so there's a small probability that the post's id will get duplicated I would think.

My question here is will that method create unique strings to use? or should I be doing something differently to generate these unique random ID's for my posts??

Thanks

Community
  • 1
  • 1
Justin
  • 4,922
  • 2
  • 27
  • 69
  • The only guarantee you have of ensuring unique IDs it to check whether the randomly generated ID has already been assigned. Or... use a plugin. – zeantsoi Feb 10 '14 at 15:16

3 Answers3

3

Here's a better method. You can use Hashids.

marvelousNinja
  • 1,510
  • 9
  • 15
  • Hashids are good, but do save the real numbers as some redundant fields in your table. This is because hashids are opaque, and won't go well if you try to use `JOIN` etc. YMMV. – Kazim Zaidi Apr 02 '15 at 03:43
2

Yes it will create a unique ID. From the highest voted answer:

while Model.where(:id => self.id).exists?

Meaning it will keep generating a new random number until it finds one that doesn't exist yet. (Which is most likely the first time around.)

Mischa
  • 42,876
  • 8
  • 99
  • 111
2

Some options:

  1. Start at an arbitrarily-chosen initial number like 299432, and increment by one each time.

  2. Generate random 6-digit numbers, and check your database to see if the number has already been used; if it has, generate another random number and repeat.

  3. Use a GUID (you can encode as base64 or however you like).

  4. If option 1 isn't acceptable because it generates sequential values, you could increment by N each time instead of by 1, and then take the modulus against M. As long as N and M are relatively prime, the sequence will generate M unique numbers. (You can also add an offset to make the numbers large.) In other words, generate (a + (i * N)) (mod M) with N and M relatively prime. This method obviously fails if you ever have more than M posts.

TypeIA
  • 16,916
  • 1
  • 38
  • 52