ActionView::Template::Error (incompatible character encodings: UTF-8 and ASCII-8BIT)
After doing some debugging I found out the issue occurs when using the ActionDispatch::Request object which happens to have strings that are all coded in ASCII-8BIT, regardless of whether my app is coded in UTF-8 or not. I do not know why this only happens when using a production server on Linux, but I'm going to assume it's some quirk in Ruby or Rails since I was unable to reproduce this error locally. The error occurred specifically because of a line like this:
@current_path = request.env['PATH_INFO']
When this instance variable was printed in the HAML template it caused an error because the string was encoded in ASCII-8BIT instead of UTF-8. To solve this I did the following:
@current_path = request.env['PATH_INFO'].dup.force_encoding(Encoding::UTF_8)
Which forced @current_path
to use a duplicated string that was forced into the proper UTF-8 encoding. This error can also occur with other request related data like request.headers
.
Mysql could be the source of troublesome ascii. Try putting the following in initializer to at least eliminate this possibility:
require 'mysql'class Mysql::Result def encode(value, encoding = "utf-8") String === value ? value.force_encoding(encoding) : value end def each_utf8(&block) each_orig do |row| yield row.map {|col| encode(col) } end end alias each_orig each alias each each_utf8 def each_hash_utf8(&block) each_hash_orig do |row| row.each {|k, v| row[k] = encode(v) } yield(row) end end alias each_hash_orig each_hash alias each_hash each_hash_utf8end
edit
This may not be applicable to mysql2 gem. Works for mysql however.