Ruby-on-rails 如何从 Rails 中的 URL 获取查询字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7316656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:55:48  来源:igfitidea点击:

How to get a query string from a URL in Rails

ruby-on-railsrubyruby-on-rails-3

提问by Prasaanth Naidu

Is there is a way to get the query string in a passed URL string in Rails?

有没有办法在 Rails 中获取传递的 URL 字符串中的查询字符串?

I want to pass a URL string:

我想传递一个 URL 字符串:

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

How can I get idand empid?

我怎样才能得到idempid

回答by mu is too short

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

如果字符串中有 URL,则使用 URI 和 CGI​​ 将其分开:

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_querybelow.

另请参阅Rack::Utils.parse_query下面的Quv 评论。

References:

参考:

回答by valk

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

etc..

等等..

回答by Russell

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 4and params[:empid]would equal 6.

在 Ruby on Rails 控制器方法中,URL 参数在名为 的散列中可用params,其中键是参数名称,但作为 Ruby“符号”(即以冒号为前缀)。所以在你的例子中,params[:id]会等于4params[:empid]会等于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:

我建议阅读一个很好的 Rails 教程,它应该涵盖这样的基础知识。是一个例子 - 谷歌会出现更多:

回答by SoAwesomeMan

Rack::Utils.parse_nested_query("a=2") #=> {"a" => "2"}

quoted from: Parse a string as if it were a querystring in Ruby on Rails

引用自: 解析一个字符串,就像它是 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}}}

像 rails 控制器那样解析查询字符串。嵌套查询,通常通过像这个 lil guy: 这样的表单字段名称name="awesome[beer][chips]" # => "?awesome%5Bbeer%5D%5Bchips%5D=cool",将“切片和切块”变成一个很棒的哈希:{"awesome"=>{"beer"=>{"chips"=>nil}}}

http://rubydoc.info/github/rack/rack/master/Rack/Utils.parse_nested_queryhttps://github.com/rack/rack/blob/master/lib/rack/utils.rb#L90

http://rubydoc.info/github/rack/rack/master/Rack/Utils.parse_nested_query https://github.com/rack/rack/blob/master/lib/rack/utils.rb#L90