Skip to content

Rendering scopes with includes is slow for no reason #78

@giovannibonetti

Description

@giovannibonetti

We have in our codebase something like this:

class AppointmentsController < BaseController
  # GET /api/v2/appointments
  def index
    appointments = Appointment.all.includes(:professional, :service)
    jsonapi_render json: appointments
  end
end

We use includes to eager load associations and avoid the N+1 query problem.
However, the record_count query becomes very slow since there is now a LEFT OUTER JOIN for each eager loded association:

SELECT DISTINCT COUNT(DISTINCT appointments.id) FROM "appointments" LEFT OUTER JOIN "professionals" ON "professionals"."id" = "appointments"."employment_id" LEFT OUTER JOIN "services" ON "services"."id" = "appointments"."service_id"

I suppose a simple fix could be done by changing this line from this:

def count_records(records, options)
  ...
  records.except(:group, :order).count("DISTINCT #{records.table.name}.id")
end

to this:

def count_records(records, options)
  ...
  records.except(:group, :includes, :order).count("DISTINCT #{records.table.name}.id")
end

By the way, can you please backport this patch to the 0.4 series as well?

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions