user3281384
user3281384

Reputation: 531

Rails: Converting URL strings to params?

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?

Upvotes: 7

Views: 5907

Answers (4)

Senonik
Senonik

Reputation: 31

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

Upvotes: 1

Vitali Margolin
Vitali Margolin

Reputation: 196

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

Upvotes: 15

Rajarshi Das
Rajarshi Das

Reputation: 12340

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

Upvotes: -1

user3281384
user3281384

Reputation: 531

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

Upvotes: 7

Related Questions