7

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 4

15

Using Rack::Utils.parse_nested_query(some_string) will give you better results since CGI will convert all the values to arrays.

Sign up to request clarification or add additional context in comments.

1 Comment

+1. 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'] }.
7

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

2 Comments

that bonus helped me
doesn't work with nested attributes, check a more robust answer below by @Senonik
1

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

This should be the correct answer
-1

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

https://gist.github.com/cdmwebs/1209732

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.