has_optional_groups.rb 774 B

123456789101112131415161718192021222324
  1. # Copyright (C) 2012-2025 Zammad Foundation, https://zammad-foundation.org/
  2. module HasOptionalGroups
  3. extend ActiveSupport::Concern
  4. included do
  5. has_and_belongs_to_many :groups, after_add: :cache_update, after_remove: :cache_update, class_name: 'Group'
  6. # Finds objects available in given groups
  7. # Objects with no selected groups as well as having one of the given groups are returned
  8. scope :available_in_groups, lambda { |groups|
  9. left_outer_joins(optional_groups_join_table_name)
  10. .where(optional_groups_join_table_name => { group_id: [nil] + Array(groups) })
  11. .where(active: true)
  12. .distinct
  13. }
  14. end
  15. class_methods do
  16. def optional_groups_join_table_name
  17. :"groups_#{name.pluralize.downcase}"
  18. end
  19. end
  20. end