I know Rails does this for you, but I have a need to do this myself for examples. Is there a simple, non-private method available that takes a string and returns the hash of params exactly as Rails does for controllers?
4 Answers
Using Rack::Utils.parse_nested_query(some_string) will give you better results since CGI will convert all the values to arrays.
1 Comment
CGI::parse also fails to correctly parse actual array parameters; e.g., for foo[]=1&foo[]=2, CGI::parse gives { 'foo[]' => ['1', '2'] } whereas Rack::Utils.parse_nested_query gives { 'foo' => ['1', '2'] }.I found a way after a more intense Google search.
To convert url string to params:
hash = CGI::parse(some_string)
And (as bonus) from hash back to url string:
some_string = hash.to_query
Thanks to: https://www.ruby-forum.com/topic/69428
If you have parameters with nested attributes, then CGI will not work.
h = { a: [{b: '1', c: '2'}, {b: '3', c: '4'}], d: '5'}
query = h.to_query
CGI.parse(query)
=> {"a[][b]"=>["1", "3"], "a[][c]"=>["2", "4"], "d"=>["5"]}
Rack is working correctly (as I wrote Ryan Blue)
require 'rack'
h = { a: [{b: '1', c: '2'}, {b: '3', c: '4'}], d: '5'}
query = h.to_query
result = Rack::Utils.parse_nested_query(query).deep_symbolize_keys
result == h # => true
1 Comment
In model you can write a query like
def to_param
"-#{self.first_name}" +"-"+ "#{self.last_name}"
end
More info
http://apidock.com/rails/ActiveRecord/Base/to_param
It will generate a url like http://ul.com/12-Ravin-Drope
More firendly url you can consult