Skip to content

Commit 6e32aeb

Browse files
committed
Fixed smart aggs not applying when multiple where calls - fixes #1737
1 parent 57a1c02 commit 6e32aeb

File tree

4 files changed

+16
-2
lines changed

4 files changed

+16
-2
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
- Added `per` method
44
- Fixed error with `aggs` method and non-hash arguments
5+
- Fixed smart aggs not applying when multiple `where` calls
56

67
## 6.0.3 (2026-01-06)
78

lib/searchkick/relation.rb

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -573,10 +573,17 @@ def where(value = NO_DEFAULT_VALUE)
573573

574574
def where!(value)
575575
check_loaded
576+
value = ensure_permitted(value)
576577
if @options[:where]
577-
@options[:where] = {_and: [@options[:where], ensure_permitted(value)]}
578+
# keep simple when possible for smart aggs
579+
if !@options[:where].keys.intersect?(value.keys)
580+
merge_option(:where, value)
581+
else
582+
# TODO flatten
583+
@options[:where] = {_and: [@options[:where], value]}
584+
end
578585
else
579-
@options[:where] = ensure_permitted(value)
586+
@options[:where] = value
580587
end
581588
self
582589
end

test/aggs_test.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,11 @@ def test_relation_multiple_arguments
172172
assert_aggs expected, Product.search("Product").aggs(:color, store_id: {where: {in_stock: true}})
173173
end
174174

175+
def test_relation_smart_aggs
176+
assert_aggs ({"store_id" => {1 => 1, 2 => 1}}), Product.search("Product").where(store_id: 2, price: {gt: 5}).aggs(:store_id)
177+
assert_aggs ({"store_id" => {1 => 1, 2 => 1}}), Product.search("Product").where(store_id: 2).where(price: {gt: 5}).aggs(:store_id)
178+
end
179+
175180
def test_relation_smart_aggs_false
176181
assert_aggs ({"store_id" => {2 => 2}}), Product.search("Product").where(color: "red").aggs(store_id: {where: {in_stock: false}}).smart_aggs(false)
177182
end

test/where_test.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ def test_where_relation
8989
# multiple where
9090
assert_search_relation ["Product A"], Product.search("product").where(in_stock: true).where(backordered: true)
9191
assert_search_relation [], Product.search("product").where(in_stock: true).where(in_stock: false)
92+
assert_search_relation [], Product.search("product").where(in_stock: true).where("in_stock" => false)
9293

9394
# rewhere
9495
assert_search_relation ["Product A", "Product C"], Product.search("product").where(in_stock: true).rewhere(backordered: true)

0 commit comments

Comments
 (0)