Merge pull request #49133 from fatkodima/fix-has_secure_token-when-not-selected-column

Fix `has_secure_token on: :initialize` when column is not selected
This commit is contained in:
Ryuta Kamizono 2023-09-05 15:25:16 +09:00 committed by GitHub
commit 2fbb25b771
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 13 additions and 1 deletions

@ -52,7 +52,7 @@ def has_secure_token(attribute = :token, length: MINIMUM_TOKEN_LENGTH, on: Activ
require "active_support/core_ext/securerandom"
define_method("regenerate_#{attribute}") { update! attribute => self.class.generate_unique_secure_token(length: length) }
set_callback on, on == :initialize ? :after : :before do
send("#{attribute}=", self.class.generate_unique_secure_token(length: length)) unless send("#{attribute}?")
send("#{attribute}=", self.class.generate_unique_secure_token(length: length)) if has_attribute?(attribute) && !send("#{attribute}?")
end
end

@ -25,6 +25,18 @@ def test_generating_token_on_initialize_does_not_affect_reading_from_the_column
assert_equal token, User.find(@user.id).token
end
def test_generating_token_on_initialize_is_skipped_if_column_was_not_selected
model = Class.new(ActiveRecord::Base) do
self.table_name = "users"
has_secure_token on: :initialize
end
model.create!
assert_nothing_raised do
model.select(:id).last
end
end
def test_regenerating_the_secure_token
@user.save
old_token = @user.token