From 684580b03d193dcac1223975aa6a51324dc437f3 Mon Sep 17 00:00:00 2001 From: Andrew Kane Date: Tue, 17 Mar 2020 21:21:20 -0700 Subject: [PATCH] Build aggs relation --- lib/searchkick/relation.rb | 14 +++++++++++++- test/aggs_test.rb | 5 +++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/lib/searchkick/relation.rb b/lib/searchkick/relation.rb index 8bac8f9..b42b85d 100644 --- a/lib/searchkick/relation.rb +++ b/lib/searchkick/relation.rb @@ -232,7 +232,7 @@ module Searchkick # TODO merge options def aggs!(*args) - options[:aggs] = args.size == 1 ? args.first : args + options[:aggs] = hash_args(options[:aggs], args) self end @@ -245,6 +245,18 @@ module Searchkick private + def hash_args(old, new) + old ||= {} + new.each do |v| + if v.is_a?(Hash) + old.merge!(v) + else + old[v] = {} + end + end + old + end + def sanitize_opts(attributes) if attributes.respond_to?(:permitted?) raise ActiveModel::ForbiddenAttributesError if !attributes.permitted? diff --git a/test/aggs_test.rb b/test/aggs_test.rb index ecfcbb8..a87782f 100644 --- a/test/aggs_test.rb +++ b/test/aggs_test.rb @@ -21,6 +21,11 @@ class AggsTest < Minitest::Test assert_equal ({1 => 1}), buckets_as_hash(Product.search("Product", relation: true).aggs(store_id: {where: {in_stock: true}}).aggs["store_id"]) end + def test_relation + relation = Product.search("Product", relation: true).aggs(:store_id).aggs(color: {where: {in_stock: true}}) + assert_equal ["color", "store_id"], relation.aggs.keys.sort + end + def test_order agg = Product.search("Product", aggs: {color: {order: {_key: "desc"}}}).aggs["color"] assert_equal %w(red green blue), agg["buckets"].map { |b| b["key"] } -- libgit2 0.21.0