繁体   English   中英

活动管理 - 通过has_many关联过滤

[英]Active Admin - filter by presence of has_many association

我有一个拥有很多照片的User模型。 我想在Active Admin中设置一个复选框过滤器来过滤那些有照片的用户。 基本上是照片关联存在的地方。

class User < ActiveRecord::Base
  has_many :photos
end

是否有捷径可寻? 我知道您可以过滤具有特定照片等的用户,但我还没有看到您可以通过状态过滤的示例。

找到正确的Ransack搜索方法的咒语是棘手的。 要使用以下过滤器搜索photos.id IS NOT NULL

ActiveAdmin.register User do
  # Filter users where photos.id is not null
  filter :photos_id_not_null, label: "With Photos", as: :boolean 
end

适合我的解决方案:

插入模型:

ransacker :has_photos do |parent|
  Arel.sql("(select exists (SELECT 1 FROM photos WHERE photos.parent_id = parents.id))")
end

然后在activeadmin过滤器中使用它:

filter :has_photos_true, as: :boolean

找到ref-1ref-2

另一个版本,如果你有一个计数器缓存:

ransacker :has_photos do |parent|
  Arel.sql("#{parent.table.name}.report_files_count > 0")
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM