Incompatible character encodings: ASCII-8BIT and UTF-8 in Ruby 1.9

I get the following error with my Ruby 1.9 and Rails 2.3.4. This happens when the user sends a standard non-ASCII character.

I read a lot of online resources, but none of them found a solution that worked.

I tried to use (as some resources suggested)

string.force_encoding('utf-8') 

but it did not help.

Any ideas how to solve this? Is there a way to eliminate such characters before saving to the database? Or is there a way to show them?

+7
ruby-on-rails
Nov 22 '09 at 19:44
source share
2 answers

I don't know much about Ruby (or Rails), but I think the problem is the lack of control over your character encodings.

First you have to decide what encoding you store in your database. Then, before writing to the database, it is necessary to convert all the text into this encoding. To do this, you first need to know which encoding it should start with.

A frequently repeated tip is to decode all input from any encoding that it uses into unicode (if your language supports it) as soon as possible after you get control over it. Then you know that all the text you process in your program is unicode. On the other hand, encode the text to any output code you want as a last step before outputting it.

The key is to always know which encoding of the text fragment is used anywhere in your code.

+1
Nov 22 '09 at 20:02
source share

For ruby ​​1.9 and Rails 3.0.x, use the mysql2 adapter.

In your gemfile:

 gem 'mysql2', '~> 0.2.7' 

and update your database.yml file:

 adapter: mysql2 

http://www.rorra.com.ar/2010/07/30/rails-3-mysql-and-utf-8/

+10
Jun 02 '11 at 4:15
source share



All Articles