This blog is part of our Rails 5 series.
We sometimes need unique and random tokens in our web apps. Here is how we typically build it.
has_secure_token in Rails 5
Rails 5 has added has_secure_token method to generate a random alphanumeric token for a given column.
Rails assumes that the attribute name is
We can provide a different name as a parameter to
if the attribute name is not
The above code assumes that we
in our model.
The generated tokens are URL safe and are of fixed length strings.
Migration helper for generating token
We can also generate migration for token similar to other data types.
Notice that migration automatically adds index on the generated column with unique constraint.
We can also generate a model with the token attribute.
Model generator also adds
method to the model.
Sometimes we need to regenerate the tokens based on some expiration criteria.
In order to do that,
we can simply call
which would regenerate the token and save it to its respective attribute.
Beware of race condition
It is possible to generate a race condition in the database while generating the tokens. So it is advisable to add a unique index in the database to deal with this unlikely scenario.