Active Admin - filter by presence of has_many association

寵の児 提交于 2020-07-08 11:18:56

问题


I have a User model that has_many photos. I'm looking to set up a checkbox filter in Active Admin to filter those users who have photos. 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.


回答1:


Finding the correct incantation of Ransack search methods is tricky. To search where the photos.id IS NOT NULL can be accomplished with the following filter:

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



回答2:


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 :

filter :has_photos_true, as: :boolean

Find ref-1 & ref-2.

Another version if you have a counter cache:

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


来源:https://stackoverflow.com/questions/27797869/active-admin-filter-by-presence-of-has-many-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!