Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove blank values params from query string

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?

like image 227
Mohit Jain Avatar asked Jun 19 '12 13:06

Mohit Jain


3 Answers

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
like image 121
Dan Kohn Avatar answered Sep 27 '22 23:09

Dan Kohn


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.

like image 26
sites Avatar answered Sep 28 '22 01:09

sites


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" 
like image 22
todb Avatar answered Sep 28 '22 00:09

todb