开发者

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 t开发者_开发技巧o pass a URL string:

http://www.foo.com?id=4&empid=6

How can I get id and empid?


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:

  • CGI.parse
  • URI.parse

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"


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

etc..


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:


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜