Class: Parse::Constraint::ArrayEmptyOrNilConstraint

Inherits:
Constraint
  • Object
show all
Defined in:
lib/parse/query/constraints.rb

Overview

Note:

Uses index-friendly operations where possible.

Array empty or nil constraint - matches arrays that are empty OR nil/missing. This is useful for finding records where an array field has no values, whether it's explicitly empty or was never set.

q.where :tags.empty_or_nil => true # matches [] or nil/missing q.where :tags.empty_or_nil => false # matches non-empty arrays only

Instance Method Summary collapse

Instance Method Details

#build ⇒ Hash

Returns the compiled constraint using aggregation pipeline.

Returns:

  • (Hash) —

    the compiled constraint using aggregation pipeline.



1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
# File 'lib/parse/query/constraints.rb', line 1475

def build
  value = formatted_value
  unless value == true || value == false
    raise ArgumentError, "#{self.class}: Value must be true or false"
  end

  # Use formatted field name for proper Parse field mapping
  field_name = Parse::Query.format_field(@operation.operand)

  if value
    # Match empty array OR nil/missing field
    # Use explicit $eq for empty array check (more reliable through Parse Server)
    pipeline = [
      {
        "$match" => {
          "$or" => [
            { field_name => { "$exists" => true, "$eq" => [] } },
            { field_name => { "$exists" => false } },
            { field_name => { "$eq" => nil } },
          ],
        },
      },
    ]
  else
    # Match non-empty arrays (must exist, not nil, and not empty)
    # Use $and to combine multiple conditions without duplicate keys
    pipeline = [
      {
        "$match" => {
          "$and" => [
            { field_name => { "$exists" => true } },
            { field_name => { "$ne" => nil } },
            { field_name => { "$ne" => [] } },
          ],
        },
      },
    ]
  end

  { "__aggregation_pipeline" => pipeline }
end

#empty_or_nil ⇒ ArrayEmptyOrNilConstraint

A registered method on a symbol to create the constraint.

Examples:

q.where :field.empty_or_nil => true

Returns:



1472
# File 'lib/parse/query/constraints.rb', line 1472

register :empty_or_nil