Debugging Legacy ActiveRecord Associations in a Staging Rails App
I can't seem to get I've been struggling with this for a few days now and could really use some help. Recently started working with a legacy Ruby on Rails application (version 5.2.4) that has a tangled web of ActiveRecord associations. While testing in the staging environment, a peculiar issue cropped up where loading a record seems to be causing unexpected `N+1` queries. The relevant model is `Order`, which has many associated `Items`. The code snippet below highlights the association: ```ruby class Order < ApplicationRecord has_many :items end class Item < ApplicationRecord belongs_to :order end ``` During a query like this: ```ruby @orders = Order.includes(:items).where(status: 'pending') ``` I expected to see just a single query to fetch orders and another for items, but instead, the logs show multiple queries being executed. I’ve confirmed that the `ActiveRecord` `includes` method was called correctly, yet the problem persists. I tried using `eager_load` as well, thinking it might force the eager loading behavior: ```ruby @orders = Order.eager_load(:items).where(status: 'pending') ``` However, this also resulted in the same issue. My next step was to inspect if there were any complicated scopes or callbacks that could be interfering with the query. I found a callback that modifies the `items` association for `Order`, leading to some unexpected behavior: ```ruby before_save :set_items_count private def set_items_count self.items_count = items.size end ``` This callback seems unnecessary, especially since it could be impacting query performance. Removing it temporarily didn't resolve the `N+1` issue, which makes me think the problem lies deeper in how the records are being retrieved. I also went through the gem `bullet` to check for any clues regarding `N+1` queries, but it didn’t provide additional insights. Any suggestions on how to effectively trace this issue back to its source or methodologies to diagnose such association quirks? What best practices should I follow to ensure proper eager loading in legacy code like this? For reference, this is a production CLI tool.