Hash - to_query 2
Look what just appeared in Rails trunk – Hash#to_query – turn a hash of values into a form-encoded query string. I’ve wanted this on occasion in the past. Check it out:
Simple Conversion
{:a => 10}.to_querya=10
Nested Conversion
{:person => {:name => 'Nicholas', :login => 'seckar'}}.to_queryperson[name]=Nicholas&person[login]=seckar
Multiple Nested
{:person => {:id => 10}, :account => {:person => {:id => 20}}}.to_queryaccount[person][id]=20&person[id]=10
Array Values
{:person => {:id => [10, 20]}}.to_queryperson[id][]=10&person[id][]=20
You can do the same thing in Prototype:
$H({ action: 'ship', order_id: 123, fees: ['f1', 'f2'], 'label': 'a demo' }).toQueryString();
Becomes this:
'action=ship&order_id=123&fees=f1&fees=f2&label=a%20demo'
It doesn’t look like Prototype handles the nested conversions yet though.
Hey Scott – thanks for this tip.
One question though: How to you change the format of the query string produced to include the ”?” prefix?
ie. instead of just do I just concatenate a ”?” in the link?thanks
OKie…now how do we do the opposite?