How to get params for url with whitespace as '%20' instead of '+' in Rails

not really.

Suggest using: your_params_hash.to_query.gsub("+", "%20")


How about

URI.encode 'John Smith'
# => John%20Smith

I would recommend just sticking to the use of a gsub, perhaps with a comment to explain the need for such behaviour.

While you could solve the problem by use of URI.escape, it is supposedly deprecated, as it does not fully conform to RFC specs. See here for a great write-up on it.

Hash#to_param is an alias of Hash#to_query, which calls Object#to_query. The simplest example to demonstrate this + vs %20 issue is:

'John Key'.to_query(:name) # => "name=John+Key"

The implementation of Object#to_query is:

def to_query(key)
  "#{CGI.escape(key.to_param)}=#{CGI.escape(to_param.to_s)}"
end

And so, we find that:

CGI.escape("John Key") # => "John+Key"

Hence, this is why I have referenced the differences between CGI.escape and URI.escape.