Make profile fields without user columns work (#10978)

This commit is contained in:
Michael Kohl 2020-10-21 19:17:35 +07:00 committed by GitHub
parent 1570d0cf0a
commit 87c89d8915
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 6 deletions

View file

@ -2,6 +2,8 @@ module Profiles
class Update
include ImageUploads
USER_COLUMNS = Set.new(User.column_names).freeze
def self.call(user, updated_attributes = {})
new(user, updated_attributes).call
end
@ -77,12 +79,8 @@ module Profiles
# Propagate changes back to the `users` table
def sync_to_user
# These are the profile attributes that still exist as columns on User.
profile_attributes = @profile.data.transform_keys do |key|
Profile::MAPPED_ATTRIBUTES.fetch(key, key).to_s
end
@profile.user._skip_profile_sync = true
if @profile.user.update(profile_attributes.except("custom_attributes"))
if @profile.user.update(user_profile_attributes)
update_user_attributes
else
@error_message = @user.errors_as_sentence
@ -93,6 +91,14 @@ module Profiles
@profile.user._skip_profile_sync = false
end
# These are the profile attributes that still exist as columns on User.
def user_profile_attributes
profile_attributes = @profile.data.transform_keys do |key|
Profile::MAPPED_ATTRIBUTES.fetch(key, key).to_s
end
profile_attributes.except("custom_attributes").select { |key, _| key.in?(USER_COLUMNS) }
end
def update_user_attributes
if @user.update(@updated_user_attributes)
@success = true

View file

@ -40,7 +40,7 @@ RSpec.describe Profiles::Update, type: :service do
end
it "sets custom attributes for the user" do
custom_profile_field = create(:custom_profile_field, profile: profile)
custom_profile_field = create(:custom_profile_field, label: "Custom test", profile: profile)
custom_attribute = custom_profile_field.attribute_name
described_class.call(user, profile: { custom_attribute => "Test" }, user: {})
@ -77,4 +77,13 @@ RSpec.describe Profiles::Update, type: :service do
expect(service.success?).to be false
expect(service.error_message).to eq "filename too long - the max is 250 characters."
end
it "works correctly if a profile field does not exist for the User model" do
profile_field = create(:profile_field, label: "No User Test")
Profile.refresh_attributes!
expect do
described_class.call(user, profile: { profile_field.attribute_name => "Test" }, user: {})
end.to change { profile.reload.public_send(profile_field.attribute_name) }
end
end