Skip to content

N+1 query on subscribable in admin subscriptions index #331

@yohanmarshall

Description

@yohanmarshall

Problem

The admin subscriptions index controller eager loads line_items and user:

@subscriptions = @search.result(distinct: true).
                 includes(:line_items, :user).
                 page(page).per(per_page)

However, the index view iterates over subscription.line_items and accesses line_item.subscribable.name to display the line items column. Since :subscribable is not included in the eager load, this causes an N+1 query — one extra query per subscription row to load the subscribable variant.

For a page with 25 subscriptions, this adds ~25 unnecessary SQL queries. For the export path (which sets per_page to 100,000), this could be significantly worse.

Suggested Fix

Change the includes in the index action from:

includes(:line_items, :user)

to:

includes(line_items: [:subscribable]).includes(:user)

This ensures the subscribable association is eager loaded along with line items, eliminating the N+1.

Environment

  • solidus_subscriptions (styrken fork, commit 9318faa)
  • File: app/controllers/spree/admin/subscriptions_controller.rb

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions