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
vars = request.query_parameters
vars['id']
vars['empid']
etc..
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:
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"
Rack::Utils.parse_nested_query("a=2") #=> {"a" => "2"}
quoted from: Parse a string as if it were a querystring in Ruby on Rails
Parse query strings the way rails controllers do. Nested queries, typically via a form field name like this lil guy: name="awesome[beer][chips]" # => "?awesome%5Bbeer%5D%5Bchips%5D=cool"
, get 'sliced-and-diced' into an awesome hash: {"awesome"=>{"beer"=>{"chips"=>nil}}}
http://rubydoc.info/github/rack/rack/master/Rack/Utils.parse_nested_query https://github.com/rack/rack/blob/master/lib/rack/utils.rb#L90
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: