Method: ActiveRecord::QueryMethods::StoreChain#where

Defined in:
lib/pgrel/active_record/store_chain.rb

#where(*opts) ⇒ Object

Query by store values. Supports array values.

NOTE: This method uses “@>” (contains) operator with logic (AND/OR) and not uses “->” (value-by-key). The use of “contains” operator allows us to use GIN index effectively.

Example

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

Model.store(:store, c: 2).all #=> [Model(name: 'first', ...)]
#=> (SQL) select * from ... where store @> '"c"=>"2"'::hstore

Model.store(:store, b: [1, 2]).size #=> 2
#=> (SQL) select * from ... where (store @> '"c"=>"1"'::hstore) or
                                  (store @> '"c"=>"2"'::hstore)


74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/pgrel/active_record/store_chain.rb', line 74

def where(*opts)
  opts.map! { |opt| opt.is_a?(Hash) ? opt : [opt] }

  update_scope(
    opts.map do |opt|
      opt.map do |k, v|
        case v
        when Array
          "(#{build_or_contains(k, v)})"
        else
          contains_clause(k => v)
        end
      end.join(" and ")
    end.join(" or ")
  )
  @scope
end