我遇到了一个场景,我采用相同字段类型的多个输入来渲染表单。
提供一些背景信息:
GET post_ad_form/?tree_field=brand;brand=bmw&tree_field=country;country=India
我需要分别返回品牌"bmw"
的模型和国家"India"
的城市。
该结构基于“How to design REST URI for multiple Key-Value params of HTTP GET”
如何访问params['tree_field']
?
答案 0 :(得分:1)
您可以合并URI#parse
和CGI#parse
来获取参数:
require 'cgi'
require 'uri'
url = 'post_ad_form/?tree_field=brand;brand=bmw&tree_field=country;country=India'
queries = CGI.parse(URI.parse(url).query)
#=> {"tree_field"=>["brand", "country"], "brand"=>["bmw"], "country"=>["India"]}
queries['tree_field'] #=> ["brand", "country"]
但是,如果您只是在字符串中使用参数,那么您可以使用CGI#parse
:
params = 'tree_field=brand;brand=bmw&tree_field=country;country=India'
CGI.parse(params)
#=> {"tree_field"=>["brand", "country"], "brand"=>["bmw"], "country"=>["India"]}
答案 1 :(得分:-1)
你的问题不清楚,但也许这会有所帮助:
require 'uri'
uri = URI.parse('http://somehost.com/post_ad_form/?tree_field=brand;brand=bmw&tree_field=country;country=India')
query = URI.decode_www_form(uri.query).map{ |a| a.last[/;(.+)$/, 1].split('=') }.to_h # => {"brand"=>"bmw", "country"=>"India"}
分解为:
query = URI.decode_www_form(uri.query) # => [["tree_field", "brand;brand=bmw"], ["tree_field", "country;country=India"]]
.map{ |a| a.last[/;(.+)$/, 1].split('=') } # => [["brand", "bmw"], ["country", "India"]]
.to_h # => {"brand"=>"bmw", "country"=>"India"}