Hash - to_query 2

Posted by sbecker Wed, 24 Jan 2007 23:48:00 GMT

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_query
Becomes this:
a=10

Nested Conversion

{:person => {:name => 'Nicholas', :login => 'seckar'}}.to_query
Becomes this:
person[name]=Nicholas&person[login]=seckar

Multiple Nested

{:person => {:id => 10}, :account => {:person => {:id => 20}}}.to_query
Becomes this:
account[person][id]=20&person[id]=10

Array Values

{:person => {:id => [10, 20]}}.to_query
Becomes this:
person[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.

Comments

Leave a response

  1. Avatar
    Gavin Morrice Sun, 19 Oct 2008 11:45:23 GMT

    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.
    www.mysite.com/users/1?name=bob
    
    instead of just
    www.mysite.com/users/1name=bob
    
    do I just concatenate a ”?” in the link?

    thanks

  2. Avatar
    quickredfox Thu, 20 Nov 2008 21:20:32 GMT

    OKie…now how do we do the opposite?