How to remove blank values params from query strin

2019-02-16 20:35发布

I have a search form, with lot of options, Submitted to a route with Get request. URL is something like this:

http://localhost:3000/restaurants/search?utf8=%E2%9C%93&city=&cuisine=&number_of_people=&query=hello

with lot more params. I want to make it cleaner something like remove all the params which are blank.

something like this: (Basically removing all the params which are blank)

http://localhost:3000/restaurants/search?query=hello

How to do this?

One way can be using

CGI::parse("foo=bar&bar=foo&hello=hi")

Gives you

{"foo"=>["bar"], "hello"=>["hi"], "bar"=>["foo"]}

First redirect user on a in between action and in that in between action check which params are blank and remove them and then finally redirecting him on the actual action of search. But this sounds very lame thing. How can i do this in a better way?

4条回答
倾城 Initia
2楼-- · 2019-02-16 21:07

My solution was to disable blank inputs and selects:

$('form').submit (e) ->
  $(@).find('select,input').map( (i, e) -> e.disabled = !$(e).val() )

Regarding removing utf8 I found this. So I better keep sending it.

Doing all of this on server resulted in an additional request when using redirect_to, so I prefer to use client side code.

查看更多
▲ chillily
3楼-- · 2019-02-16 21:24

In your controller method, call remove_empty_query_params

Then as a private method:

  def remove_empty_query_params
    # Rewrites /projects?q=&status=failing to /projects?status=failing
    require 'addressable/uri'
    original = request.original_url
    parsed = Addressable::URI.parse(original)
    return unless parsed.query_values.present?
    queries_with_values = parsed.query_values.reject { |_k, v| v.blank? }
    if queries_with_values.blank?
      parsed.omit!(:query)
    else parsed.query_values = queries_with_values
    end
    redirect_to parsed.to_s unless parsed.to_s == original
  end
查看更多
Melony?
4楼-- · 2019-02-16 21:25

Just with plain ol' ruby...

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" 
查看更多
疯言疯语
5楼-- · 2019-02-16 21:27

I would suggest, if just looking at plain old ruby, a simple gsub might be enough:

url.gsub(/[^\?&=]+=(?:&|$)/, '')

Note: this may leave an ampersand at the end, which can be trimmed with

url.chomp('&')
查看更多
登录 后发表回答