Skip to content

Commit 32f4317

Browse files
committed
Fix has_secure_token on: :initialize when column is not selected
1 parent 42db7f3 commit 32f4317

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

activerecord/lib/active_record/secure_token.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def has_secure_token(attribute = :token, length: MINIMUM_TOKEN_LENGTH, on: Activ
5252
require "active_support/core_ext/securerandom"
5353
define_method("regenerate_#{attribute}") { update! attribute => self.class.generate_unique_secure_token(length: length) }
5454
set_callback on, on == :initialize ? :after : :before do
55-
send("#{attribute}=", self.class.generate_unique_secure_token(length: length)) unless send("#{attribute}?")
55+
send("#{attribute}=", self.class.generate_unique_secure_token(length: length)) if has_attribute?(attribute) && !send("#{attribute}?")
5656
end
5757
end
5858

activerecord/test/cases/secure_token_test.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,18 @@ def test_generating_token_on_initialize_does_not_affect_reading_from_the_column
2525
assert_equal token, User.find(@user.id).token
2626
end
2727

28+
def test_generating_token_on_initialize_is_skipped_if_column_was_not_selected
29+
model = Class.new(ActiveRecord::Base) do
30+
self.table_name = "users"
31+
has_secure_token on: :initialize
32+
end
33+
34+
model.create!
35+
assert_nothing_raised do
36+
model.select(:id).last
37+
end
38+
end
39+
2840
def test_regenerating_the_secure_token
2941
@user.save
3042
old_token = @user.token

0 commit comments

Comments
 (0)