如何在 ActiveAdmin 0.5.0 中为资源全局指定预先加载?

How to specify eager loading globally for a resource in ActiveAdmin 0.5.0?

我有一个页面注册到我的 ActiveAdmin 应用程序中的模型,如下所示:

ActiveAdmin.register Report do
  menu parent: 'Administration', priority: 2

  scope ...
  scope ...

  filter ...
  filter ...

end

"Report" model/resource 与其他模型有许多关联。为某些关联指定预先加载的最佳方法是什么,这些关联也适用于所有范围和过滤器的结果?

最好的方法是使用内置功能:)

ActiveAdmin.register Report do
  includes :users, :apples, :rhinos

  ...
end

您可以在 https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md

阅读更多关于资源定制的信息

你可以像

一样覆盖scoped_collection
ActiveAdmin.register Report do
  menu parent: 'Administration', priority: 2

  controller do
     def scoped_collection 
       Report.includes(:users, ....)  
     end
  end
end

UPD,完全同意@TimoSchilling 的评论。

如果你想覆盖scoped_collection使用super然后追加方法,这样InheritedResource的end_of_association_chain就不会被忽略。

所以最终代码是

ActiveAdmin.register Report do
      menu parent: 'Administration', priority: 2

      controller do
         def scoped_collection 
           super.includes(:users, ....)  
           # or 
           super.eager_load(:users, ....)  
         end
      end
    end

但是在大多数情况下 这个答案会很有效。