77

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?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Prasaanth Naidu
  • 861
  • 1
  • 10
  • 15

4 Answers4

115

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"
mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • 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 '17 at 11:15
  • This answer is outdated. See answer by Russel below. It is correct. – Steve Carey Aug 15 '20 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. – mu is too short Aug 19 '20 at 08: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. – Steve Carey Aug 20 '20 at 18:50
52
vars = request.query_parameters
vars['id']
vars['empid']

etc..

valk
  • 9,363
  • 12
  • 59
  • 79
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:

Russell
  • 12,261
  • 4
  • 52
  • 75
  • 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 = "http://www.foo.com?empid=6" empid = "what should i do here to get the empid" p empid – Prasaanth Naidu Sep 06 '11 at 08:14
  • Ah, ok. Then I think Mikhail's answer is what you need. – Russell Sep 06 '11 at 08:27
  • @PrasaanthNaidu you should be asking how to do this in Ruby, not Rails – Orlando Jun 20 '17 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. – Steve Carey Aug 15 '20 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*. – mu is too short Aug 19 '20 at 08:24
  • @mu is too short - Yes, that is the question. And while the OP didn't specifically say he wants to do it in the controller, where else would he do it? Because he tagged it as a Ruby and Rails question, not JavaScript, then he wants to access the query string on the back end, not the front end. So the Controller is generally the place to do that. Something like @ id = params[:id] and @ empid = params[:empid]. Here is the link to the appropriate Rails docs: https://guides.rubyonrails.org/routing.html#the-query-string. My comment was to point out that it's not necessary to parse it manually. – Steve Carey Aug 20 '20 at 18:24
  • @SteveCarey Where else? How about in a model that store URLs and needs to remove garbage such as `fblcid` parameters or a model that wants to extract just YouTube video IDs from URLs or a comment system that needs to clean up URLs in comment text? There are lots of places where a Rails would need to work with URLs in strings that having nothing to do with controllers or `params`, probably every Rails app I've worked on has had to do this sort of thing. – mu is too short Aug 20 '20 at 21:43
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

Community
  • 1
  • 1
SoAwesomeMan
  • 3,226
  • 1
  • 22
  • 25
  • 3
    This should be the accepted answer. It's significantly easier to use than CGI.parse. Thanks!! – roydq Jan 22 '16 at 09:27