Fixed false matches with where_properties for text columns
Andrew Kane
committed Jun 21, 2016
commit 09d24a6925a592e699cf2f2d0bf75cb7baf4b2c2
Showing 3
changed files with
17 additions
and 4 deletions
CHANGELOG.md
+4
-0
| @@ | @@ -1,3 +1,7 @@ |
| + | ## 1.4.2 [unreleased] |
| + | |
| + | - Fixed false matches with `where_properties` for text columns |
| + | |
| ## 1.4.1 | |
| - Added `where_properties` method | |
README.md
+1
-1
| @@ | @@ -492,7 +492,7 @@ The same approach also works with visitor tokens. |
| With ActiveRecord, use: | |
| ```ruby | |
| - | Ahoy::Event.where_properties(store_id: 1).count |
| + | Ahoy::Event.where(name: "Viewed product").where_properties(product_id: 123).count |
| ``` | |
| **Note:** If you get a `NoMethodError`, upgrade Ahoy and add `include Ahoy::Properties` to your model. | |
ahoy/properties.rb b/lib/ahoy/properties.rb
+12
-3
| @@ | @@ -12,9 +12,18 @@ module Ahoy |
| relation = relation.where("properties ->> ? = ?", k, v) | |
| end | |
| else | |
| - | properties.each do |k, v| |
| - | # not 100%, but will do |
| - | relation = relation.where("properties LIKE ?", "%#{{k => v}.to_json.sub(/\A\{/, "").sub(/\}\z/, "")}%") |
| + | adapter_name = connection.adapter_name.downcase |
| + | case adapter_name |
| + | when /postgres/ |
| + | properties.each do |k, v| |
| + | relation = relation.where("properties SIMILAR TO ?", "%[{,]#{{k => v}.to_json.sub(/\A\{/, "").sub(/\}\z/, "")}[,}]%") |
| + | end |
| + | when /mysql/ |
| + | properties.each do |k, v| |
| + | relation = relation.where("properties REGEXP ?", "[{,]#{{k => v}.to_json.sub(/\A\{/, "").sub(/\}\z/, "")}[,}]") |
| + | end |
| + | else |
| + | raise "Adapter not supported: #{adapter_name}" |
| end | |
| end | |
| relation | |