Last Updated: February 25, 2016
·
8.816K
· mbillard

Convert a hash to query string parameters

You already know that you need to encode/escape your strings. Did you know that Rails has a built-in method to do this? Simply call to_query on your hash and it will do the job for you.

Converts an object into a string suitable for use as a URL query string, using the given key as the param name.

Note: This method is defined as a default implementation for all Objects for Hash#to_query to work.

source

Note that it also orders the params to help with HTTP caching.

Ex:

{ second: 'value for second', first: '"<#$' }.to_query
# => "first=%22%3C%23%24&second=value+for+second"

Reference