Today I gona discuss about the
ActiveRecord::Base#has_secure_password method, in rails 5 it became
has_secure_token, it specifies that an attribute of your model should be used to store a unique 24-character alphanumeric token.
Tokens such as this are often used in Rails applications for providing token-based
API access or allowing one-time access for password reset actions. Since it is such a
common use case, it’s very convenient to have it built into Rails.
Add token into existing model:
To add a secure token column to an existing model, you can use the migration generator:
rails g migration add_auth_token_to_users auth_token:token.
This creates a migration to add a string column called auth_token and adds a unique index on that column, as shown in the following code:
Add Secure Token in model:
The name of the model attribute defaults to token if no name for the column is specified.The actual token value is generated in a before_create handler, so the value is only available after you have successfully created an item. After that, the value does not subsequently change, as shown here:
You can specify multiple token attributes in a model, simply by adding additional has_secure_token statements.
Regenerating the Token:
If you want to generate token and save it to the database, you can now use
regenerate_token method to generate new token: