# Param-based count loader (for params and foreign keys). # # Example: # CountLoader.for(Category).load(category_id) # class CountLoader < GraphQL::Batch::Loader def initialize(model, param: :id, scope: nil) @model = model @param = param @scope = case scope when Symbol scope.to_proc when Hash ->(mod) { mod.where(scope) } when ActiveRecord::Relation ->(_) { scope } end end def perform(ids) scope = @scope ? @scope.call(@model) : @model scope.where(@param => ids).group(@param).count .each_pair { |record_id, count| fulfill(record_id.to_s, count) } ids.each { |id| id_ = id.to_s fulfill(id_, nil) unless fulfilled?(id_) } end end