0

I ran into scenario where I m taking multiple input of same field type to render a form.

To give some context:

GET post_ad_form/?tree_field=brand;brand=bmw&tree_field=country;country=India

I need to return the model for brand "bmw" and the cities for country "India" respectively.

The structure is based on "How to design REST URI for multiple Key-Value params of HTTP GET"

How can I access params['tree_field']?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Arun G
  • 1,678
  • 15
  • 17
  • 1
    Possible duplicate of [how to get query string from passed url in ruby on rails](https://stackoverflow.com/questions/7316656/how-to-get-query-string-from-passed-url-in-ruby-on-rails) – Gagan Gami Jun 19 '17 at 07:13
  • What is your desired output? Accessing `tree_field` is easy. What do you want after you access it? – the Tin Man Jun 19 '17 at 18:32

2 Answers2

1

You can combine URI#parse and CGI#parse to fetch params:

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"]

However, if you just have the params in a String then you can just use CGI#parse:

params = 'tree_field=brand;brand=bmw&tree_field=country;country=India'
CGI.parse(params)
#=> {"tree_field"=>["brand", "country"], "brand"=>["bmw"], "country"=>["India"]}
Surya
  • 15,703
  • 3
  • 51
  • 74
-1

Your question isn't clear, but maybe this will help:

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"}

which breaks down to:

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"}
the Tin Man
  • 158,662
  • 42
  • 215
  • 303