Skip to content

Commit

Permalink
Rewrite N+1 query
Browse files Browse the repository at this point in the history
  • Loading branch information
dlackty committed Apr 20, 2022
1 parent cadeb88 commit fb86c67
Showing 1 changed file with 5 additions and 2 deletions.
7 changes: 5 additions & 2 deletions lib/active_admin/sortable_tree/controller_actions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,13 @@ def sortable(options = {})
collection_action :sort, :method => :post do
resource_name = ActiveAdmin::SortableTree::Compatibility.normalized_resource_name(active_admin_config.resource_name)

# Query all resources at once to avoid N+1
ids = (params[resource_name].keys + params[resource_name].values).compact.uniq
resources = Hash[resource_class.where(id: ids).map { |r| [r.id.to_i, r] }]

records = []
params[resource_name].each_pair do |resource, parent_resource|
parent_resource = resource_class.find(parent_resource) rescue nil
records << [resource_class.find(resource), parent_resource]
records << [resources[resource.to_i], resources[parent_resource.to_i]]
end

errors = []
Expand Down

0 comments on commit fb86c67

Please sign in to comment.