From 0a210801928a00d02ad8b9df809650004ae60f74 Mon Sep 17 00:00:00 2001 From: Andy Allan Date: Thu, 18 Jan 2024 10:29:56 +0000 Subject: [PATCH] Move change detection to validation declaration This aligns with other validations. Also add test to ensure unchanged display_names are treated as valid. --- app/models/user.rb | 4 ++-- test/models/user_test.rb | 8 ++++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/app/models/user.rb b/app/models/user.rb index 8a471586a..d0993f7ee 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -99,7 +99,7 @@ class User < ApplicationRecord validates :display_name, :if => proc { |u| u.display_name_changed? }, :characters => { :url_safe => true }, :whitespace => { :leading => false, :trailing => false } - validate :display_name_cannot_be_user_id_with_other_id + validate :display_name_cannot_be_user_id_with_other_id, :if => proc { |u| u.display_name_changed? } validates :email, :presence => true, :confirmation => true, :characters => true validates :email, :if => proc { |u| u.email_changed? }, :uniqueness => { :case_sensitive => false } @@ -126,7 +126,7 @@ class User < ApplicationRecord after_save :spam_check def display_name_cannot_be_user_id_with_other_id - display_name_changed? && display_name&.match(/^user_(\d+)$/i) do |m| + display_name&.match(/^user_(\d+)$/i) do |m| errors.add :display_name, I18n.t("activerecord.errors.messages.display_name_is_user_n") unless m[1].to_i == id end end diff --git a/test/models/user_test.rb b/test/models/user_test.rb index c2571d0c0..37f66e178 100644 --- a/test/models/user_test.rb +++ b/test/models/user_test.rb @@ -113,6 +113,14 @@ class UserTest < ActiveSupport::TestCase assert_predicate user, :valid?, "user_ name is invalid for own id, when it should be" end + def test_display_name_user_id_unchanged_is_valid + user = build(:user, :display_name => "user_0") + user.save(:validate => false) + user.reload + + assert_predicate user, :valid?, "user_0 display_name is invalid but it hasn't been changed" + end + def test_friends_with alice = create(:user, :active) bob = create(:user, :active) -- 2.45.1