81

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

116

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"
Sign up to request clarification or add additional context in comments.

4 Comments

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).
This answer is outdated. See answer by Russel below. It is correct.
@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.
@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.
57
vars = request.query_parameters
vars['id']
vars['empid']

etc..

4 Comments

for Rails domain this is the best answer
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.
And I want to use it for a controller ... so it fits perfectly. Tks
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.
36

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 Comments

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
Ah, ok. Then I think Mikhail's answer is what you need.
@PrasaanthNaidu you should be asking how to do this in Ruby, not Rails
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.
@SteveCarey Except that the question isn't about accessing parameters in a controller method, it is about extracting parameters from a URL string.
|
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 Comment

This should be the accepted answer. It's significantly easier to use than CGI.parse. Thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.