简体   繁体   English

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

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

I have a User model that has_many photos. 我有一个拥有很多照片的User模型。 I'm looking to set up a checkbox filter in Active Admin to filter those users who have photos. 我想在Active Admin中设置一个复选框过滤器来过滤那些有照片的用户。 Basically where the photos association is present. 基本上是照片关联存在的地方。

class User < ActiveRecord::Base
  has_many :photos
end

Is there an easy way to do this? 是否有捷径可寻? I know you can filter by users who have a certain photo etc. but I haven't seen an example where you can filter by presence. 我知道您可以过滤具有特定照片等的用户,但我还没有看到您可以通过状态过滤的示例。

Finding the correct incantation of Ransack search methods is tricky. 找到正确的Ransack搜索方法的咒语是棘手的。 To search where the photos.id IS NOT NULL can be accomplished with the following filter: 要使用以下过滤器搜索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

Solution that work for me : 适合我的解决方案:

Insert in model : 插入模型:

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

Then use it in activeadmin filter : 然后在activeadmin过滤器中使用它:

filter :has_photos_true, as: :boolean

Find ref-1 & ref-2 . 找到ref-1ref-2

Another version if you have a counter cache: 另一个版本,如果你有一个计数器缓存:

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