Generate unique random token in ruby on rails

I am a full-stack Ruby on Rails developer with experience in PostgreSQL, Docker, Heroku, and performance optimization. I love exploring new technology stacks and have recently developed an interest in mobile app development using Flutter. My skills in test-driven development and fixing security vulnerabilities have helped me deliver high-quality, reliable code. I am also currently learning about machine learning and its applications in real-world problem-solving. I bring a unique combination of technical expertise, creative problem-solving, and a passion for learning to any team. I am committed to delivering elegant and efficient software solutions and excited to contribute to an innovative and dynamic team that shares this vision.
Introduction
Generating unique random tokens for ruby on rails applications is a common problem. People use different ways to solve this problem and the most common way to solve this problem that we can find on the internet is to generate a SecureRandom.hex like this:
def generate_token
loop do
token = SecureRandom.hex(32)
break token unless Record.where(token: token).exists?
end
end
Here we are telling this method to generate a random token using SecureRandom.hex(), and then do an ActiveRecord query on a Record model to see if that token already exists in the database. If it does, then generate another token, until the unique none existing token is found. you can read more about this method from SecureRandom.
I think we can improve this method to generate a more unique token by adding Unix Timestamp in combination with SecureRandom.hex() token like this:
def generate_token
loop do
token = SecureRandom.hex(20)
unix_timestamp = Time.current.to_time.to_i # e.g output => 1672645137
token += unix_timestamp.to_s
break token unless Record.where(token: token).exists?
end
end
I think combining unix timestamp with SecureRandom hex can give a more unique token, hence less repetition to match the unique token in the database.

