Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eager loading associated models in ActiveAdmin sql query

Tags:

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?

like image 430
tomblomfield Avatar asked Dec 14 '11 18:12

tomblomfield


1 Answers

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

like image 64
Jay Avatar answered Sep 22 '22 17:09

Jay