Module: ActiveRecordExtended::QueryMethods::WhereChain

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

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)


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

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)


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

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' }


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

def contains(opts, *rest)
  if ActiveRecordExtended::AR_VERSION_GTE_6_1
    return substitute_comparisons(opts, rest, Arel::Nodes::Contains, "contains")
  end

  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}


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

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