Module: ActiveRecordExtended::WhereChain

Included in:
ActiveRecord::QueryMethods::WhereChain
Defined in:
lib/active_record_extended/query_methods/where_chain.rb

Constant Summary collapse

AR_VERSION_AT_LEAST_6_1 =
ActiveRecord.version >= Gem::Version.new('6.1')

Instance Method Summary collapse

Instance Method Details

#all(opts, *rest) ⇒ Object

Finds Records that contain a single matchable array element User.where.all(tags: 3)

# SELECT user.* FROM user WHERE 3 = ALL(user.tags)


25
26
27
# File 'lib/active_record_extended/query_methods/where_chain.rb', line 25

def all(opts, *rest)
  equality_to_function("ALL", opts, rest)
end

#any(opts, *rest) ⇒ Object

Finds Records that contain an element in an array column User.where.any(tags: 3)

# SELECT user.* FROM user WHERE 3 = ANY(user.tags)


18
19
20
# File 'lib/active_record_extended/query_methods/where_chain.rb', line 18

def any(opts, *rest)
  equality_to_function("ANY", opts, rest)
end

#contains(opts, *rest) ⇒ Object

Finds Records that contains a nested set elements

Array Column Type:

User.where.contains(tags: [1, 3])
# SELECT user.* FROM user WHERE user.tags @> {1,3}

HStore Column Type:

User.where.contains(data: { nickname: 'chainer' })
# SELECT user.* FROM user WHERE user.data @> 'nickname' => 'chainer'

JSONB Column Type:

User.where.contains(data: { nickname: 'chainer' })
# SELECT user.* FROM user WHERE user.data @> {'nickname': 'chainer'}

This can also be used along side joined tables

JSONB Column Type Example:

Tag.joins(:user).where.contains(user: { data: { nickname: 'chainer' } })
# SELECT tags.* FROM tags INNER JOIN user on user.id = tags.user_id WHERE user.data @> { nickname: 'chainer' }


49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/active_record_extended/query_methods/where_chain.rb', line 49

def contains(opts, *rest)
  build_where_chain(opts, rest) do |arel|
    case arel
    when Arel::Nodes::In, Arel::Nodes::Equality
      column = left_column(arel) || column_from_association(arel)

      if [:hstore, :jsonb].include?(column.type)
        Arel::Nodes::ContainsHStore.new(arel.left, arel.right)
      elsif column.try(:array)
        Arel::Nodes::ContainsArray.new(arel.left, arel.right)
      else
        raise ArgumentError.new("Invalid argument for .where.contains(), got #{arel.class}")
      end
    else
      raise ArgumentError.new("Invalid argument for .where.contains(), got #{arel.class}")
    end
  end
end

#overlaps(opts, *rest) ⇒ Object Also known as: overlap

Finds Records that have an array column that contain any a set of values User.where.overlap(tags: [1,2])

# SELECT * FROM users WHERE tags && {1,2}


10
11
12
# File 'lib/active_record_extended/query_methods/where_chain.rb', line 10

def overlaps(opts, *rest)
  substitute_comparisons(opts, rest, Arel::Nodes::Overlaps, "overlap")
end