Eager loading associated models in ActiveAdmin sql query

IMPORTANT EDIT NOTE : what follows is actually false, see the comments for an explanation. However I leave this answer where it stands because it seems I'm not the only one to get confused by the guides, so maybe someone else will find it useful.

i assume that

class Bill < ActiveRecord::Base
  belongs_to :user
end

so according to RoR guides it is already eager-loaded :

There’s no need to use :include for immediate associations – that is, if you have Order belongs_to :customer, then the customer is eager-loaded automatically when it’s needed.

you should check your SQL log if it's true (didn't know that myself, i was just verifying something about :include to answer you when i saw this... let me know)


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.


The existing answers were right at the time, but ActiveAdmin supports eager loading with a much more convenient syntax now:

ActiveAdmin.register Bill do
  includes :user
end

See the docs for resource customization


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