Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(budget_categories): prevent N+1 in subcategories method (#4066)

sentry[bot]86f8e77a8b75
diff --git a/app/models/budget.rb b/app/models/budget.rb
index 609728c904..d7381ab536 100644
--- a/app/models/budget.rb
+++ b/app/models/budget.rb
@@ -14,7 +14,7 @@ class Budget < ApplicationRecord
belongs_to :family
belongs_to :user, optional: true
- has_many :budget_categories, -> { includes(:category) }, dependent: :destroy
+ has_many :budget_categories, -> { includes(:category) }, dependent: :destroy, inverse_of: :budget
validates :start_date, :end_date, presence: true
validates :start_date, :end_date, uniqueness: { scope: [ :family_id, :user_id ] }
diff --git a/app/models/budget_category.rb b/app/models/budget_category.rb
index 2ec25df776..a80d41fe7f 100644
--- a/app/models/budget_category.rb
+++ b/app/models/budget_category.rb
@@ -18,7 +18,7 @@ class BudgetCategory < ApplicationRecord
include Monetizable
- belongs_to :budget
+ belongs_to :budget, inverse_of: :budget_categories
belongs_to :category
validates :budget_id, uniqueness: { scope: :category_id }
@@ -407,12 +407,10 @@ class BudgetCategory < ApplicationRecord
end
def subcategories
- return BudgetCategory.none unless category.parent_id.nil?
- return BudgetCategory.none if category.id.nil?
+ return [] unless category.parent_id.nil?
+ return [] if category.id.nil?
- budget.budget_categories
- .joins(:category)
- .where(categories: { parent_id: category.id })
+ budget.budget_categories.select { |bc| bc.category.parent_id == category.id }
end
private
diff --git a/test/models/budget_category_test.rb b/test/models/budget_category_test.rb
index f1167367f0..e76328a5b1 100644
--- a/test/models/budget_category_test.rb
+++ b/test/models/budget_category_test.rb
@@ -235,6 +235,16 @@ class BudgetCategoryTest < ActiveSupport::TestCase
assert_empty uncategorized_bc.subcategories
end
+ test "subcategories issues no additional queries when budget_categories are already loaded" do
+ # Load budget_categories through the association so the inverse is populated.
+ parent_bc = @budget.budget_categories.find { |bc| bc.id == @parent_budget_category.id }
+
+ assert_queries_count(0) do
+ result = parent_bc.subcategories
+ assert_equal 2, result.size
+ end
+ end
+
test "parent with only inheriting subcategories shares entire budget" do
# Set subcategory_with_limit to also inherit
@subcategory_with_limit_bc.update!(budgeted_spending: 0)