Rails inserts BLOB data into field with expected TEXT type

Encountering this on Rails 4.0.1 on Ruby 1.9.3. This replica cartier happens because ActiveRecord sees the data you’re inserting as binary. It’s a string encoding issue.

In my particular case, the problem arose from cartier love bracelet
sending the output of Digest::MD5.hexdigest() (disclaimer: do not use MD5 in security-sensitive applications) directly to the ORM for handling. There cartier love bracelet is a bug in Rubies < 2.0.0 that renders the output of hexdigest as ASCII-8BIT instead of US-ASCII. ASCII-8BIT is interpreted by many gems, including ActiveRecord, as binary data.

Thankfully, the workaround is quite simple. Just tack on a force_encoding call after your hexdigest and you should be good, like so:

Digest::MD5.hexdigest("data").force_encoding(Encoding::US_ASCII)

This will return the hexdigest string in a format widely interpreted as text data, and ActiveRecord, YAML, and other gems will begin handling the string as expected.

Once again, this workaround is not necessary on Ruby >= 2.0.0, which already contains a patch for the Digest gems that specifies the correct encoding. Therefore, an alternate solution is to upgrade to Ruby >= 2.0.0, or compile a Ruby that contains the resolving patch.