Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Opposite of Hash#to_param

If I convert a hash to a query string, how can I convert it back again?

{:filters => {:colour => ['Red', 'Blue'], :size => 'Medium'}}.to_param
=> "filters[colour][]=Red&filters[colour][]=Blue&filters[size]=Medium"

Rails appears to do this automatically when it populates the params hash, but is it possible to call this method directly?

Thanks.

like image 966
gjb Avatar asked May 18 '11 17:05

gjb


People also ask

What is a Hash in rails?

A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.

Are Ruby hashes ordered?

Hashes are inherently unordered. Hashes provide amortized O(1) insertion and retrieval of elements by key, and that's it. If you need an ordered set of pairs, use an array of arrays.

How do you check if a key exists in a Ruby Hash?

We can check if a particular hash contains a particular key by using the method has_key?(key) . It returns true or false depending on whether the key exists in the hash or not.


1 Answers

You're looking for Rack::Utils.parse_nested_query(query), which will convert it back into a Hash. You can get it by using this line:

require 'rack/utils'
like image 141
Ryan Bigg Avatar answered Nov 09 '22 12:11

Ryan Bigg