How to get a query string from a URL in Rails

Ruby on-RailsRubyRuby on-Rails-3

Ruby on-Rails Problem Overview


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?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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"

Solution 2 - Ruby on-Rails

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

etc..

Solution 3 - Ruby on-Rails

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:

Solution 4 - Ruby on-Rails

Rack::Utils.parse_nested_query("a=2") #=> {"a" => "2"}

quoted from: https://stackoverflow.com/questions/2772778/parse-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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPrasaanth NaiduView Question on Stackoverflow
Solution 1 - Ruby on-Railsmu is too shortView Answer on Stackoverflow
Solution 2 - Ruby on-RailsvalkView Answer on Stackoverflow
Solution 3 - Ruby on-RailsRussellView Answer on Stackoverflow
Solution 4 - Ruby on-RailsSoAwesomeManView Answer on Stackoverflow