Rails:散列# to_param相反

时间:2021-12-09 19:41:31

If I convert a hash to a query string, how can I convert it back again?

如果我将散列转换为查询字符串,我如何将它再转换回来?

{:filters => {:colour => ['Red', 'Blue'], :size => 'Medium'}}.to_param
=> "filters[colour][]=Red&filters[colour][]=Blue&filters[size]=Medium"

Rails appears to do this automatically when it populates the params hash, but is it possible to call this method directly?

当Rails填充params散列时,它会自动执行这个操作,但是是否可以直接调用这个方法呢?

Thanks.

谢谢。

2 个解决方案

#1


30  

You're looking for Rack::Utils.parse_nested_query(query), which will convert it back into a Hash. You can get it by using this line:

您正在寻找Rack: Utils.parse_nested_query(查询),它将把它转换回散列。你可以用这句话来表达:

require 'rack/utils'

#2


1  

query_string = "filters[colour][]=Red&filters[colour][]=Blue&filters[size]=Medium"
CGI::parse(query_string)

#1


30  

You're looking for Rack::Utils.parse_nested_query(query), which will convert it back into a Hash. You can get it by using this line:

您正在寻找Rack: Utils.parse_nested_query(查询),它将把它转换回散列。你可以用这句话来表达:

require 'rack/utils'

#2


1  

query_string = "filters[colour][]=Red&filters[colour][]=Blue&filters[size]=Medium"
CGI::parse(query_string)