Eager loading associated models in ActiveAdmin sql query

tomblomfield picture tomblomfield · Dec 14, 2011 · Viewed 8.2k times · Source

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?

Answer

Jay picture Jay · Jun 27, 2016

The way to do this is to override the scoped_collection method (as noted in Jeff Ancel's answer) but call super to retain the existing scope. This way you retain any pagination/filtering which has been applied by ActiveAdmin, rather than starting from scratch.

ActiveAdmin.register Bill do
  controller do
    def scoped_collection
      super.includes :user
    end
  end

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

As noted in official documentation at http://activeadmin.info/docs/2-resource-customization.html