How to get a query string from a URL in Rails

ghz 1years ago ⋅ 6041 views

Question

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?


Answer

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

require 'cgi'

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:

require "addressable/uri"

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"