Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix has_secure_token on: :initialize when column is not selected #49133

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/secure_token.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
12 changes: 12 additions & 0 deletions activerecord/test/cases/secure_token_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down