How to get a query string from a URL in Rails

2019-01-08 09:25发布

问题:

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?

回答1:

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.

References:

  • CGI.parse
  • URI.parse


回答2:

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:



回答3:

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

etc..



回答4:

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



回答5:

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.