Move change detection to validation declaration
This aligns with other validations. Also add test to ensure unchanged display_names are treated as valid.
This commit is contained in:
parent
2c342adc0d
commit
0a21080192
2 changed files with 10 additions and 2 deletions
|
@ -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
|
||||
|
|
|
@ -113,6 +113,14 @@ class UserTest < ActiveSupport::TestCase
|
|||
assert_predicate user, :valid?, "user_<id> 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)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue