Active Admin - filter with has_many association

I have a model Userthat has some photos. I want to configure the checkbox filter in Active Admin to filter those users who have photos. In principle, where there is an association of photographs.

class User < ActiveRecord::Base
  has_many :photos
end

Is there an easy way to do this? I know that you can filter users who have a specific photo, etc., but I have not seen an example where you can filter by presence.

+5
source share
2 answers

Finding the right spell for Ransack's search methods is difficult. To search where photos.id IS NOT NULLcan be performed using 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
+10

, :

:

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-1 ref-2.

, :

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

Source: https://habr.com/ru/post/1570147/


All Articles