Inconsistent behaviour in UserUpdater class

AI-generated summary

The discussion highlights an inconsistency in the UserUpdater class where updating a user’s custom field using a symbol key (e.g., :user_field_1) results in duplicate entries in the database, while using a string key (e.g., 'user_field_1') correctly replaces the existing value. fzngagan reproduces the issue by calling UserUpdater#update with a hash containing a symbol key, which causes the value to be appended as a comma-separated string in the UI. In contrast, wrapping the parameters in ActionController::Parameters and permitting them behaves correctly, though it’s considered unnatural. fzngagan traces the root cause to the HasCustomFields mixin, which treats symbol and string keys differently — symbol keys trigger creation of new UserCustomField records, while string keys delete existing ones before inserting the new value. A PR (#10486) was submitted and merged to resolve this inconsistency, ensuring consistent behavior regardless of key type. eviltrout acknowledges the issue as valid and thanks the reporter for identifying it.

@eviltrout

Repro steps:

  1. Let’s create a user field and it has id 1.
  2. Run the second line of the below code twice.

Case 1

up = UserUpdater.new(Discourse.system_user, User.find(1))
up.update({:custom_fields=>{:user_field_1=>"abc"}})
  1. You’ll see abc twice when you go to /my/preferences/profile

Surprisingly, when the profile is updated via /my/preferences/profile, it does so perfectly fine.

Case 2

This seems to work fine

up = UserUpdater.new(Discourse.system_user, User.find(1))
params = ActionController::Parameters.new({:custom_fields=>{:user_field_1=>"abc"}})
up.update(params.permit!)

What happens is, in Case 1, the value is pushed to an array and is displayed as comma-separated values on /my/preferences/profile.

Case 2 seems to do the correct thing i.e. it replaces the current value with the new one but wrapping it in ActionController::Parameters is unnatural.

This does seem like a valid bug and should be fixed, thanks for reporting it!

My analysis comes down to this.

# case 1
u1 = User.find(1)
u1.custom_fields[:user_field_1] = "abc"
u1.save

# case 2
u1.custom_fields["user_field_1"] = "abc"
u1.save

In case 1, A new UserCustomField is created per call to u1.save

In case 2, All UserCustomField with the name ‘user_field_1’ are deleted from the db
except the specified.

Screenshot 2020-08-20 at 11.56.49 AM

All and all the symbol and string versions of the same key are treated differently in the HasCustomFields mixin.

Ok, I went for it. Here’s the PR which fixes the issue

https://github.com/discourse/discourse/pull/10486

Ok, so this one is merged.