ElasticSearch处理Rails使用嵌套对象路由params

时间:2018-03-25 18:18:14

标签: ruby-on-rails elasticsearch routes searchkick

我们有一个Rails搜索路径,可以接受应该映射到ElasticSearch运算符的嵌套对象。

例如:

{
  name: "John",
  age: {
    {gte: 20}
  }
}

问题是当Rails路由参数如下所示时,SearchKick库会抛出错误:

{"name"=>["Sam Terrick", "John Terrick"], "age"=>{"gte"=>"20"}}

Searchkick库通过这些过滤器进行映射,并对:gte进行大小写比较,但是散列火箭键不匹配。 ActiveSupport :: HashWithIndifferentAccess没有完成工作。

https://github.com/ankane/searchkick/blob/master/lib/searchkick/query.rb

是否有一种优雅的方法来处理来自路径参数的嵌套对象的转换,而无需检查每个参数是否为哈希?

1 个答案:

答案 0 :(得分:3)

For that you could make use of the Rails Hash.html#method-i-deep_transform_keys:

params = {"name"=>["Sam Terrick", "John Terrick"], "age"=>{"gte"=>"20"}}
p params.deep_transform_keys(&:to_sym)
# {:name=>["Sam Terrick", "John Terrick"], :age=>{:gte=>"20"}}

But Rails also implements other handy method, more accurate in this case, Hash.html#deep_symbolize_keys:

p params.deep_symbolize_keys
# # {:name=>["Sam Terrick", "John Terrick"], :age=>{:gte=>"20"}}

Same result.