Tutorial :Rails: post data with a '+' is getting set to a blank



Question:

I have post data that includes a '+' sign. Once it makes it to the server the raw post data is showing the '+' sign but once the post data makes it into the param hash the '+' sign has been converted to a blank. Any ideas on how to make it NOT do that?


Solution:1

If you replace your '+' signs with '%2B', this should resolve the issue.

However, also note that you probably need to check your ampersands, percent signs, and other characters as well. The server receiving your post data is probably expecting URLEncoded data.

In a nutshell, if you replace % signs with %25, then replace & with %26, replace ? with %3F, replace # with %23, and replace + signs with %2B; you will cover most of the issues you can encounter.

A more in-depth list of replacements can be found at these links.

HTML Url Encoding (w3schools)

Percent-Encoding (wikipedia)


Solution:2

Have a look at the CGI.escape method in the standard library that will do this for you:

  irb(main):001:0> require 'cgi'  => true  irb(main):002:0> CGI.escape 'foo+bar&baz?qux quux/corge'  => "foo%2Bbar%26baz%3Fqux+quux%2Fcorge"  

There's also a CGI.unescape method should you need to convert back.


Solution:3

Try replacing the + with %2B.


Solution:4

Not sure why that is happening. Normally + signs make it through to the params. Can you post your rails versions. Also try escaping the "+" sign with "+" or its CGI equivalent "%2B" to see if it makes a difference.


Solution:5

there is a Ruby call to handle all this for you so you don't need to figure out the characters yourself

require 'uri'

url = http://www.google.com?a=this is a test URI.escape(url, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »