simplify it with use of eager loading @trackers = Tracker.all…
- User
simplify it with use of eager loading
@trackers ||= Tracker.all
@issue_status_tracker_relevant_hash = {} # Initialize an empty hash @trackers.each do |tracker| # Fetch the unique new_status_ids for the tracker new_status_ids = WorkflowTransition.where(tracker_id: tracker.id).pluck(:new_status_id).uniq # Fetch the corresponding IssueStatus records and store them in the hash @issue_status_tracker_relevant_hash[tracker.id] = IssueStatus.where(id: new_status_ids) end - Assistant
You can optimize your code with eager loading to avoid N+1 queries and reduce the number of database calls. Here's a simplified version using
includesandgroupto gather the uniquenew_status_idsfor all trackers in one go:@trackers ||= Tracker.includes(workflow_transitions: :issue_statuses).all @issue_status_tracker_relevant_hash = @trackers.each_with_object({}) do |tracker, hash| # Collect unique new_status_ids directly from the included workflow_transitions new_status_ids = tracker.workflow_transitions.pluck(:new_status_id).uniq # Fetch the corresponding IssueStatus records for the unique new_status_ids hash[tracker.id] = IssueStatus.where(id: new_status_ids) endExplanation:
-
Eager Loading: The
includes(workflow_transitions: :issue_statuses)part preloadsworkflow_transitionsalong with their associatedissue_statusesto reduce the number of queries made to the database.
-