Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a query string from a URL in Rails

Is there is a way to get the query string in a passed URL string in Rails?

I want to pass a URL string:

http://www.foo.com?id=4&empid=6

How can I get id and empid?

like image 835
Prasaanth Naidu Avatar asked Sep 06 '11 07:09

Prasaanth Naidu


People also ask

How do I find the query string of a website?

The PHP Server object provides access to the query string for a page URL. Add the following code to retrieve it: $query_string = $_SERVER['QUERY_STRING']; This code stores the query string in a variable, having retrieved it from the Server object.

Does URL include query string?

A query string is a part of a uniform resource locator (URL) that assigns values to specified parameters.

How do you give a URL a query?

Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.


3 Answers

If you have a URL in a string then use URI and CGI to pull it apart:

url    = 'http://www.example.com?id=4&empid=6'
uri    = URI.parse(url)
params = CGI.parse(uri.query)
# params is now {"id"=>["4"], "empid"=>["6"]}

id     = params['id'].first
# id is now "4"

Please use the standard libraries for this stuff, don't try and do it yourself with regular expressions.

Also see Quv's comment about Rack::Utils.parse_query below.

References:

  • CGI.parse
  • URI.parse

Update: These days I'd probably be using Addressable::Uri instead of URI from the standard library:

url = Addressable::URI.parse('http://www.example.com?id=4&empid=6')
url.query_values                  # {"id"=>"4", "empid"=>"6"}
id    = url.query_values['id']    # "4"
empid = url.query_values['empid'] # "6"
like image 52
mu is too short Avatar answered Oct 01 '22 20:10

mu is too short


vars = request.query_parameters
vars['id']
vars['empid']

etc..

like image 35
valk Avatar answered Oct 01 '22 19:10

valk


In a Ruby on Rails controller method the URL parameters are available in a hash called params, where the keys are the parameter names, but as Ruby "symbols" (ie. prefixed by a colon). So in your example, params[:id] would equal 4 and params[:empid] would equal 6.

I would recommend reading a good Rails tutorial which should cover basics like this. Here's one example - google will turn up plenty more:

like image 33
Russell Avatar answered Oct 01 '22 18:10

Russell