0

I am seeing strange behavior when saving strings to fields in my database when it contains special characters. In this example "á" or "\xE1"

So if the field is "TESTá" the field that gets persisted on save is "TEST".

Even more worryingly, if the field is validated as mandatory. And I set it to "á", validation passes but on save an empty string gets saved. Making the persisted record invalid!

My database encoding is UTF-8, so I think this is an encoding issue.

Indeed, if on the console I try a simple test I get this error:

» "TEST\xE1F".encode('UTF-8')
Encoding::UndefinedConversionError: "\xE1" from ASCII-8BIT to UTF-8

So, how should I correctly persist special characters in rails / active record?

Thanks for any help.

4

1 回答 1

0

将编码类型添加到您的迁移中

# encoding: utf-8
class SetDefaultValues < ActiveRecord::Migration
  def up
    change_column_default(:dimensions, :unit_of_measure, "inch")
    change_column_default(:gdnts, :unit_for_tolerance, "µinch")
  end
end

也在模型中。

# encoding: utf-8
class Specifications::Specification < ActiveRecord::Base
  ...
end
于 2012-09-07T10:30:51.747 回答