FIX: creating a user shouldn't error when optional fields aren't provided

This fixes a bug where the server would 500 if the only user fields
where optional ones, and the create_user call didn't provide any
values so that params[:user_fields] was nil.

Additionally, don't bother double-checked for required fields, since we
iterate over all fields and will catch any that are required and blank.
This commit is contained in:
Greg Kempe 2015-01-27 11:48:27 +02:00
parent fbd18f3b69
commit d99ccf6d27
2 changed files with 33 additions and 12 deletions

View File

@ -213,20 +213,19 @@ class UsersController < ApplicationController
# Handle custom fields # Handle custom fields
user_fields = UserField.all user_fields = UserField.all
if user_fields.present? if user_fields.present?
if params[:user_fields].blank? && UserField.where(required: true).exists? field_params = params[:user_fields] || {}
return fail_with("login.missing_user_field") fields = user.custom_fields
else
fields = user.custom_fields user_fields.each do |f|
user_fields.each do |f| field_val = field_params[f.id.to_s]
field_val = params[:user_fields][f.id.to_s] if field_val.blank?
if field_val.blank? return fail_with("login.missing_user_field") if f.required?
return fail_with("login.missing_user_field") if f.required? else
else fields["user_field_#{f.id}"] = field_val
fields["user_field_#{f.id}"] = field_val
end
end end
user.custom_fields = fields
end end
user.custom_fields = fields
end end
authentication = UserAuthenticator.new(user, session) authentication = UserAuthenticator.new(user, session)

View File

@ -604,6 +604,28 @@ describe UsersController do
end end
end end
context "with only optional custom fields" do
let!(:user_field) { Fabricate(:user_field, required: false) }
context "without values for the fields" do
let(:create_params) { {
name: @user.name,
password: 'watwatwat',
username: @user.username,
email: @user.email,
} }
it "should succeed" do
xhr :post, :create, create_params
expect(response).to be_success
inserted = User.where(email: @user.email).first
expect(inserted).to be_present
expect(inserted.custom_fields).not_to be_present
expect(inserted.custom_fields["user_field_#{user_field.id}"]).to be_blank
end
end
end
end end
context '.username' do context '.username' do