diff --git a/app/controllers/directory_items_controller.rb b/app/controllers/directory_items_controller.rb index b0d33beabe7..692088cdc55 100644 --- a/app/controllers/directory_items_controller.rb +++ b/app/controllers/directory_items_controller.rb @@ -38,7 +38,7 @@ class DirectoryItemsController < ApplicationController user_field = UserField.find_by(name: params[:order]) if user_field result = result - .joins(:user) + .references(:user) .joins("LEFT OUTER JOIN user_custom_fields ON user_custom_fields.user_id = users.id AND user_custom_fields.name = 'user_field_#{user_field.id}'") .order("user_custom_fields.name = 'user_field_#{user_field.id}' ASC, user_custom_fields.value #{dir}") end diff --git a/spec/requests/directory_items_controller_spec.rb b/spec/requests/directory_items_controller_spec.rb index 13408609390..686ee8d1170 100644 --- a/spec/requests/directory_items_controller_spec.rb +++ b/spec/requests/directory_items_controller_spec.rb @@ -136,6 +136,41 @@ describe DirectoryItemsController do expect(json['directory_items'][1]['user']['username']).to eq(evil_trout.username) | eq(stage_user.username) end + it "orders users by user fields" do + group.add(walter_white) + field1 = Fabricate(:user_field, searchable: true) + field2 = Fabricate(:user_field, searchable: true) + + user_fields = [ + { user: walter_white, field: field1, value: "Yellow", order: 1 }, + { user: stage_user, field: field1, value: "Apple", order: 0 }, + { user: evil_trout, field: field2, value: "Moon", order: 2 } + ] + + user_fields.each do |data| + UserCustomField.create!( + user_id: data[:user].id, + name: "user_field_#{data[:field].id}", + value: data[:value] + ) + end + + get '/directory_items.json', params: { period: 'all', group: group.name, order: field1.name, user_field_ids: "#{field1.id}|#{field2.id}", asc: true } + expect(response.status).to eq(200) + + json = response.parsed_body + expect(json).to be_present + items = json['directory_items'] + expect(items.length).to eq(3) + expect(json['meta']['total_rows_directory_items']).to eq(3) + + user_fields.each do |data| + user = items[data[:order]]['user'] + expect(user['username']).to eq(data[:user].username) + expect(user['user_fields']).to eq({ data[:field].id.to_s => data[:value] }) + end + end + it "checks group permissions" do group.update!(visibility_level: Group.visibility_levels[:members])