Rails 5 token ActiveModel type
Rails 5 has a new ActiveModel type token
. To define it you can use: has_scure_token
.
So I had this class:
class Session < ApplicationRecord
belongs_to :user
before_validation(on: :create) do
self.auth_token = SecureRandom.urlsafe_base64(24)
end
end
And then I started to use the new has_secure_token
and the code is way simpler now:
class Session < ApplicationRecord
belongs_to :user
has_secure_token :auth_token
end
If you use generators for models you can run:
rails generate model session auth_token:token
By the way the current implementation uses SecureRandom.base58(24)
, so it is url safe.