読者です 読者をやめる 読者になる 読者になる

ravelll の日記

よしなに

Prevent N+1 Query Problems in index action on Active Admin.

tech Rails ruby

Active Admin is a Ruby on Rails plugin that provides administration web page.
Our development team uses it for our service.

Few days ago, we bring in bullet gem, then we found N+1 query problems in some administration index pages.

I searched the way, therefore we could prevent it in following way.
(In following codes, the product model belongs to the user model and the brand model)

ActiveAdmin.register Product do
...

  controller do
    def scoped_collection
      Product.includes(:user, :brand)   # includes User / Brand models in listing products
    end
  end

  index do
    ...

    column :user    # The cause of
    column :brand   # N+1 query problem
    ...

  end
  ...

end

If you use resource of Identity model is belongs to user model, you can solve with following way.

ActiveAdmin.register Product do
...

  controller do
    def scoped_collection
      Product.includes({ :user => :identity }, :brand)   # specify grandchild model with hash!
    end
  end

  index do
    ...

    column :user
    column :brand
    column('Full Name') { |product| product.user.identity.full_name }    # uses grandchild model's resource, belongs to User model
    ...

  end
  ...

end

These solutions are introdused in Active Admin's documentation.