Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append query string to url

Tags:

I have a callback url string params[:callback] and I need to append a query string "&result=true" and redirect the user. The better way I found of doing this is using addressable but I think the code is too big for task like this especially when we are talking about ruby:

callback = Addressable::URI.parse(params[:callback])
query = callback.query_values
query[:result] = 'true'
callback.query_values = query

redirect_to callback.to_s

Is there a more elegant way of getting the same result as this snippet?

like image 613
MIchel Avatar asked Jul 02 '11 21:07

MIchel


People also ask

Which HTTP method can append query string to URL?

Simply use: echo http_build_url($url, array("query" => "the=query&parts=here"), HTTP_URL_JOIN_QUERY); .

How can I append a query parameter to an existing URL?

This can be done by using the java. net. URI class to construct a new instance using the parts from an existing one, this should ensure it conforms to URI syntax. The query part will either be null or an existing string, so you can decide to append another parameter with & or start a new query.

How do you append to a URL?

To append a param onto the current URL with JavaScript, we can create a new URL instance from the URL string. Then we can call the searchParams. append method on the URL instance to append a new URL parameter into it. to create a new URL instance with "http://foo.bar/?x=1&y=2" .


2 Answers

I wan't to bring update to this topic, because any of the solutions didn't work me.

The reason being, that it seems that callback.query_values returns Nil if the actual url doesn't have existing query values.

Therefore if you have urls such as: http://www.foo.com and http://www.foo.com?bar=1 you should use the following code:

url = "http://www.foo.com" # or params[:callback] obviously. :)

callback = Addressable::URI.parse(url)
callback.query_values = (callback.query_values || {}).merge({
  result: true
})

redirect_to callback.to_s

Cheers.

like image 114
Mauno Vähä Avatar answered Oct 14 '22 21:10

Mauno Vähä


  • if you don't need any URL validations you can do this (looks a little bit dirty):
    
    url = params[:callback]
    redirect_to url + (url.include?('?') ? '&' : '?') + 'result=true'
    
  • otherwise you have to use either some external library (like Addressable) or URI module from standard library
like image 28
Anton Rogov Avatar answered Oct 14 '22 21:10

Anton Rogov