如何从查询字符串中删除空值params

Moh*_*ain 8 ruby ruby-on-rails query-string querystringparameter

我有一个搜索表单,有很多选项,提交到Get请求的路由.URL是这样的:

http://localhost:3000/restaurants/search?utf8=%E2%9C%93&city=&cuisine=&number_of_people=&query=hello
Run Code Online (Sandbox Code Playgroud)

有更多的参数.我想让它更干净,比如删除所有空白的参数.

这样的事情:(基本上删除所有空白的参数)

http://localhost:3000/restaurants/search?query=hello
Run Code Online (Sandbox Code Playgroud)

这该怎么做?

一种方法可以使用

CGI::parse("foo=bar&bar=foo&hello=hi")
Run Code Online (Sandbox Code Playgroud)

给你

{"foo"=>["bar"], "hello"=>["hi"], "bar"=>["foo"]}
Run Code Online (Sandbox Code Playgroud)

首先在用户之间重定向用户,并在操作之间检查哪些参数是空白的并删除它们然后最终重定向他的实际搜索操作.但这听起来很蹩脚.我怎样才能以更好的方式做到这一点?

小智 1

只是用普通的红宝石......

require 'uri'
a = "http://localhost:8080/path/search?foo=&bar=&baz=2&bat=thing"
u = URI.parse(a)
params = u.query.split("&").select {|param| param =~ /=./}.join("&")
# Returns "baz=2&bat=thing" 
Run Code Online (Sandbox Code Playgroud)