Search code examples
ruby-on-railsactiverecordactiveadmin

Eager loading associated models in ActiveAdmin sql query


I've got an ActiveAdmin index page

ActiveAdmin.register Bill

And I am trying to display links to associated models

index do
  column "User" do |bill|
   link_to bill.user.name, admin_user_path(bill.user)
  end
end

But I run into the N+1 query problem - there's a query to fetch each user.

Is there a way of eager loading the bills' users?


Solution

  • There is an answer on a different post, but it describes well what you need to do here.

      controller do
        def scoped_collection
          Bill.includes(:user)
        end
      end
    

    Here, you will need to make sure you follow scope. So if your controller is scope_to'ed, then you will want to replace the model name above with the scope_to'ed param.