Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create URL for external site with GET parameters in Rails

I'm making a Tweet This link in Rails. The URL I need to generate looks something like this:

http://twitter.com/share?url=http%3A%2F%2Fexample.com&text=Hello%20World 

but a bit more complex. Basically a URL with a load of GET parameters appended

It would be nice to use one of Rails' helpers, to generate this link, something like:

url_for("http://twitter.com/share", :url => "http://example.com", :text => "Hello world") 

But I haven't found anything that works. Anyone have any ideas?

like image 682
Alex Peattie Avatar asked Nov 24 '11 02:11

Alex Peattie


People also ask

How do I pass parameters to URL?

Any word after the question mark (?) in a URL is considered to be a parameter which can hold values. The value for the corresponding parameter is given after the symbol "equals" (=). Multiple parameters can be passed through the URL by separating them with multiple "&".

Can I pass URL as query parameter?

Yes, that's what you should be doing. encodeURIComponent is the correct way to encode a text value for putting in part of a query string. but when it is decoded at the server, the parameters of url are interpreted as seperate parameters and not as part of the single url parameter.

What is get parameter in URL?

GET parameters (also called URL parameters or query strings) are used when a client, such as a browser, requests a particular resource from a web server using the HTTP protocol. These parameters are usually name-value pairs, separated by an equals sign = . They can be used for a variety of things, as explained below.

How do I change the URL parameters in Java?

The value of a parameter can be updated with the set() method of URLSearchParams object. After setting the new value you can get the new query string with the toString() method. This query string can be set as the new value of the search property of the URL object.


2 Answers

You can call to_query on Hash in rails which will take care of url encoding etc. So maybe something like this:

params = {   :a => "http://google.com",   :b => 123 } url = "http://example.com?#{params.to_query}" 
like image 73
Brian Armstrong Avatar answered Sep 25 '22 14:09

Brian Armstrong


I like Brian's answer. Here it is in the form of a method, in case anyone else comes across this.

  def url_with_attributes_from_hash(url = "", attr_hash = {})     url == "" or attr_hash == {} ? "#{url.to_s}" : "#{url.to_s}?#{attr_hash.to_query}"   end 
like image 40
saneshark Avatar answered Sep 24 '22 14:09

saneshark