@@ -88,7 +88,37 @@ User.normalize_value_for(:phone, "+1 (555) 867-5309") # => "5558675309"
88
88
89
89
### Add ` ActiveRecord::Base.generates_token_for `
90
90
91
- TODO: Add description https://github.com/rails/rails/pull/44189
91
+ A new [ method ` generates_token_for ` ] ( https://github.com/rails/rails/pull/44189 ) has been introduced
92
+ to ` ActiveRecord::Base ` . This feature allows you to generate tokens that can embed data from a record.
93
+ These tokens are particularly useful for tasks like password resets.
94
+
95
+ With ` generates_token_for ` , tokens can be designed to reflect record state, making it possible to embed
96
+ specific record data within the token itself. When utilizing the token to retrieve the associated record,
97
+ a comparison is performed between the data in the token and the current data in the record. If the two
98
+ sets of data do not match, the token is considered invalid, similar to an expired token.
99
+
100
+ Here's an example of how this feature can be used:
101
+
102
+ ``` ruby
103
+ class User < ActiveRecord ::Base
104
+ has_secure_password
105
+
106
+ generates_token_for :password_reset , expires_in: 15 .minutes do
107
+ # A password's BCrypt salt changes when the password is updated.
108
+ # By embedding (part of) the salt in a token, the token will
109
+ # expire when the password is updated.
110
+ BCrypt ::Password .new (password_digest).salt[- 10 ..]
111
+ end
112
+ end
113
+
114
+ user = User .first
115
+ token = user.generate_token_for(:password_reset )
116
+
117
+ User .find_by_token_for(:password_reset , token) # => user
118
+
119
+ user.update!(password: " new password" )
120
+ User .find_by_token_for(:password_reset , token) # => nil
121
+ ```
92
122
93
123
### Add ` perform_all_later ` to enqueue multiple jobs at once
94
124
0 commit comments