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
?
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.
A query string is a part of a uniform resource locator (URL) that assigns values to specified parameters.
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.
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"
vars = request.query_parameters
vars['id']
vars['empid']
etc..
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With