How to remove empty parameter values ​​from the query string

I have a search form with many options, sent to a route with a Get request. The url looks something like this:

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

with a lot of options. I want to make cleaner something like deleting all the parameters that are empty.

something like this: (Basically removing all parameters that are empty)

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

How to do it?

One way can be used

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

Gives you

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

First, redirect the user to an action between actions and that between actions they check which parameters are empty and delete them, and then, finally, redirect them to the actual search action. But that sounds very weak. How can I do it better?

+7
source share
4 answers

My solution was to disable blank inputs and select:

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

As for uninstalling utf8 , I found this one . Therefore, I’d better send it.

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

+2
source

Just with a simple 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" 
+1
source

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 
+1
source

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

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

Note: there may be an ampersand at the end that can be trimmed with

 url.chomp('&') 
0
source

All Articles