How to generate a unique random id for post in Ruby on Rails 4?

筅森魡賤 提交于 2020-01-06 19:56:49

问题


I want to produce unique post identifier for posts in my blogging application.

Currently I am using SecureRandom.hex(10) for generating unique post identifier for my blogging site but I am not sure is it safe SecureRandom for this purpose.

Is there any other way to do this?


回答1:


From the Ruby doc:

This library is an interface for secure random number generator which is suitable for generating session key in HTTP cookies, etc.

I had similar problem, I used Digest library.

Digest::MD5.hexdigest(post.title + post.created_at.to_s) #=> "b4809d..."



回答2:


If anyone looking for just unique numeric token. I'd rather use Time based approach. For not much-frequent requests (max one per second). You can use

Time.now.to_i

To get it in string Time.now.to_i.to_s If you are dealing with frequent requests (thousands per second) while generating token. Use float conversation

Time.now.to_f #1532415770.0032046

To get it in string you can use Time.now.to_f.to_s.gsub(".", "") although not recommended.

The chance of repentance of above value is close to null in current universe.



来源:https://stackoverflow.com/questions/34377748/how-to-generate-a-unique-random-id-for-post-in-ruby-on-rails-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!