我们有一个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
是否有一种优雅的方法来处理来自路径参数的嵌套对象的转换,而无需检查每个参数是否为哈希?
答案 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.