How to get a query string from a URL in Rails

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?

Answers


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

url    = 'http://www.foo.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:


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:


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

etc..


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


This is not the best method, but it works:

request.query_string.split(/&/).inject({}) do |hash, setting|
  key, val = setting.split(/=/)
  hash[key.to_sym] = val
  hash
end

This will return hash with all GET params( :name => value ). Or just use request.query_string method, depends on in which format you want to get your GET params. Also you can use request.query_params from rake gem.


Need Your Help

Force flushing of output to a file while bash script is still running

bash file flush

I have a small script, which is called daily by crontab using the following command:

Set a database value to null with a SqlCommand + parameters

.net sql

I was previously taught today how to set parameters in a SQL query in .NET in this answer (click).