73

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?

4 Answers 4

113

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"
4
  • 10
    While this answer has got upvoted lots, I don't like it always returns Array for values. Alternatively, We can go with something like Rack::Utils.parse_query(URI(url).query).
    – Quv
    Mar 22, 2017 at 11:15
  • This answer is outdated. See answer by Russel below. It is correct. Aug 15, 2020 at 22:46
  • 1
    @SteveCarey Read the question again please and read the OP's comment on your preferred answer. The question is how to parse a URL in a string and extract parameters from it, this doesn't have anything to do with the params method in a Rails controller. Aug 19, 2020 at 8:23
  • @mu is too short - Okay, the OP did indeed want to convert the query string into an actual string before parsing it. But most people reading this old question just want to get the key value pairs from the query string and won't need to convert it to an actual string first. So my comment was just to say that Russell's answer below is the most straight-forward way to do that. Aug 20, 2020 at 18:50
49
vars = request.query_parameters
vars['id']
vars['empid']

etc..

4
  • 4
    for Rails domain this is the best answer Mar 15, 2016 at 16:43
  • 2
    No it's not the best answer for Rails. OP asks for parsing String URL, and this answer assumes there is request in context, like a controller. Jul 19, 2019 at 22:30
  • And I want to use it for a controller ... so it fits perfectly. Tks Oct 2, 2021 at 19:11
  • Also, a caveat: this only returns params that were submitted on the most recent request, and ignores any params that might already be in the URL. Mar 29, 2022 at 17:03
35

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:

7
  • 1
    Thanks for the fast reply Russell,really appreciate it.but i dont want to get it from the url,instead i want it to extract from the string.here is the application which im trying to do. require 'rubygems' require 'date' require 'cgi' require File.dirname(FILE) + "/lib/provider_base.rb" Dir[File.dirname(FILE) + '/lib/*.rb'].each {|file| require file } url = "foo.com?empid=6" empid = "what should i do here to get the empid" p empid Sep 6, 2011 at 8:14
  • Ah, ok. Then I think Mikhail's answer is what you need.
    – Russell
    Sep 6, 2011 at 8:27
  • @PrasaanthNaidu you should be asking how to do this in Ruby, not Rails
    – Orlando
    Jun 20, 2017 at 21:15
  • This is the only right answer. All the others are the wrong way to do it, at least in today's Rails (back in 2011 they may have been right). Params[:id] will pick up both params in the route and query params. Aug 15, 2020 at 22:42
  • @SteveCarey Except that the question isn't about accessing parameters in a controller method, it is about extracting parameters from a URL string. Aug 19, 2020 at 8:24
26
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

1
  • 3
    This should be the accepted answer. It's significantly easier to use than CGI.parse. Thanks!!
    – roydq
    Jan 22, 2016 at 9:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.