Class: ActiveRecord::QueryMethods::JsonbChain

Inherits:
KeyStoreChain show all
Defined in:
lib/pgrel/active_record/store_chain/jsonb_chain.rb

Overview

Store chain for jsonb columns.

Instance Method Summary collapse

Methods inherited from KeyStoreChain

#any, #key, #keys

Methods inherited from StoreChain

#contained, #contains, #initialize, #not, #where

Constructor Details

This class inherits a constructor from ActiveRecord::QueryMethods::StoreChain

Instance Method Details

#path(*args) ⇒ Object

Query by value in path.

Example:

Model.create!(name: 'first', store: {b: 1, c: { d: 3 } })
Model.create!(name: 'second', store: {b: 2, c: { d: 1 }})

Model.store(:store).path(c: {d: 3}).all #=> [Model(name: 'first', ...)]
Model.store(:store).path('c', 'd', [1, 3]).size #=> 2


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/pgrel/active_record/store_chain/jsonb_chain.rb', line 15

def path(*args)
  args = flatten_hash(args.first) if args.size == 1
  val = args.pop

  path = "{#{args.join(',')}}"

  case val
  when Hash
    op = '#>'
    val = ::ActiveSupport::JSON.encode(val)
  when Array
    op = '#>>'
    val = val.map(&:to_s)
  else
    op = '#>>'
    val = val.to_s
  end

  where_with_prefix "#{@store_name}#{op}", path => val
end

#value(*values) ⇒ Object

Value existence

Example

Model.create!(name: 'first', store: {a: 1, b: 2})
Model.create!(name: 'second', store: {b: 1, c: 3})

Model.store(:store).values(1, 2).all
#=>[Model(name: 'first', ...), Model(name: 'second')]


44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/pgrel/active_record/store_chain/jsonb_chain.rb', line 44

def value(*values)
  query = String.new
  values = values.map do |v|
    case v
    when Hash, Array, String
      v.to_json
    else
      v.to_s
    end
  end

  values.length.times do |n|
    query.concat(value_existence_query)
    query.concat(' OR ') if n < values.length - 1
  end
  update_scope(query, *values)
end

#values(*values) ⇒ Object

Values existence

Example

Model.create!(name: 'first', store: {a: 1, b: 2})
Model.create!(name: 'second', store: {b: 1, c: 3})

Model.store(:store).values(1, 2).all #=> [Model(name: 'first', ...)]


69
70
71
72
73
74
75
76
77
78
79
# File 'lib/pgrel/active_record/store_chain/jsonb_chain.rb', line 69

def values(*values)
  values = values.map do |v|
    case v
    when Hash, Array, String
      v.to_json
    else
      v.to_s
    end
  end
  update_scope(value_existence_query, values)
end