diff --git a/lib/api/v1/course.rb b/lib/api/v1/course.rb index a5001ca0806..105a627caf6 100644 --- a/lib/api/v1/course.rb +++ b/lib/api/v1/course.rb @@ -174,7 +174,8 @@ module Api::V1::Course def preload_teachers(courses) threshold = params[:teacher_limit].presence&.to_i if threshold - teacher_counts = Course.where(:id => courses).joins(:teacher_enrollments).group("courses.id").count + scope = TeacherEnrollment.active_or_pending.where(:course_id => courses).distinct.select(:user_id, :course_id) + teacher_counts = Enrollment.from("(#{scope.to_sql}) AS t").group("t.course_id").count to_preload = [] courses.each do |course| next unless count = teacher_counts[course.id] diff --git a/spec/apis/v1/accounts_api_spec.rb b/spec/apis/v1/accounts_api_spec.rb index 4ccc997f831..4464d245731 100644 --- a/spec/apis/v1/accounts_api_spec.rb +++ b/spec/apis/v1/accounts_api_spec.rb @@ -705,6 +705,22 @@ describe "Accounts API", type: :request do expect(c2_hash['teacher_count']).to eq 2 end + it "should return a better teacher count if a teacher is in too many sections" do + @c1 = course_with_teacher(:account => @a1, :course_name => 'c1').course + s2 = @c1.course_sections.create! + # should not think there are two teachers if one is in multiple sections + @c1.enroll_teacher(@teacher, :section => s2, :allow_multiple_enrollments => true) + @c2 = course_with_teacher(:account => @a1, :course_name => 'c2', :user => @teacher).course + + @a1.account_users.create!(user: @user) + json = api_call(:get, "/api/v1/accounts/#{@a1.id}/courses?include[]=teachers&teacher_limit=1", + { :controller => 'accounts', :action => 'courses_api', :account_id => @a1.to_param, + :format => 'json', :include => ['teachers'], :teacher_limit => "1" }) + [@c1, @c2].each do |c| + expect(json.detect{|h| h['id'] == c.id}['teachers'].map{|t| t['id']}).to eq [@teacher.id] + end + end + describe 'sort' do before :once do @me = @user