The personal finance app for everyone (by everyone)
Ruby
perf(accounts): preload transfer, category, and split-parent associations on show (#2441)
ghosta21ab1946e94
diff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rbindex 330312dc6d..f2e3d8f606 100644--- a/app/controllers/accounts_controller.rb+++ b/app/controllers/accounts_controller.rb@@ -84,6 +84,24 @@ class AccountsController < ApplicationControllerTransaction::ActivitySecurityPreloader.new(@entries).preload+ # The preload and split-parent lookup below are intentionally scoped to the+ # current page (@entries) — only this page is rendered, so a child entry+ # whose split parent sits on another page deliberately won't resolve it.+ transactions = @entries.filter_map { |e| e.entryable if e.transaction? }+ if transactions.any?+ ActiveRecord::Associations::Preloader.new(+ records: transactions,+ associations: [ :transfer_as_inflow, :transfer_as_outflow, :category, :merchant ]+ ).call+ end++ entry_ids = @entries.map(&:id)+ @split_parent_entry_ids = if entry_ids.any?+ Entry.where(parent_entry_id: entry_ids).distinct.pluck(:parent_entry_id).to_set+ else+ Set.new+ end+@activity_feed_data = Account::ActivityFeedData.new(@account, @entries)enddiff --git a/test/controllers/accounts_controller_test.rb b/test/controllers/accounts_controller_test.rbindex 5f2fb06eb5..898fc76da5 100644--- a/test/controllers/accounts_controller_test.rb+++ b/test/controllers/accounts_controller_test.rb@@ -19,6 +19,31 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestassert_response :successend+ test "show avoids N+1 transfer queries across paginated entries" do+ queries = capture_sql_queries { get account_url(@account) }+ assert_response :success++ # Per-row transfer lookups (N+1 pattern) hit transfers with a single id+ # Preloading batches them into IN(...) — assert no single-id lookups remain+ per_row_transfer = queries.count { |q|+ q.match?(/FROM "transfers".*WHERE.*"(inflow|outflow)_transaction_id"/) &&+ !q.include?(" IN (")+ }+ assert_equal 0, per_row_transfer, "N+1 per-row transfer queries detected (#{per_row_transfer})"+ end++ test "show avoids N+1 split-parent queries across paginated entries" do+ queries = capture_sql_queries { get account_url(@account) }+ assert_response :success++ # Per-row child-entry existence checks (N+1) hit entries with a single parent_entry_id+ # @split_parent_entry_ids preloads this in one batch IN query+ per_row_split = queries.count { |q|+ q.match?(/FROM "entries".*WHERE.*"parent_entry_id"/) && !q.include?(" IN (")+ }+ assert_equal 0, per_row_split, "N+1 per-row split-parent queries detected (#{per_row_split})"+ end+test "show lazily loads statement tab data unless statements tab is active" doAccountStatement::Coverage.expects(:for_year).neverAccountStatement.expects(:reconciliation_statuses_for).never