Rails ActiveAdmin Eliminating n+1 queries on custom attributes belong to another model

You are getting (N+1) query because you are ordering branch_phones. By default Rails returns records in assenting order. You don’t have to order again.

I believe you have some association like bellow:

# app/models/branch.rb

class Branch < ApplicationRecord
  has_many :branch_phones
end
# app/models/branch_phone.rb

class BranchPhone < ApplicationRecord
  belongs_to :branch
end

Please add this lines in your app/admin/brach.rb file.

# app/admin/brach.rb

controller do
  def scoped_collection
    super.includes(:branch_phones)
  end
end

index do
  column :id
  column :manager_name
  column :manager_email
  column :phone_number do |branch|
    branch.branch_phones.first&.phone_number
  end

  actions
end

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top