Fixtures: How to load utf-8 characters and convert

2019-07-27 06:47发布

问题:

I am new to Rails.

I am working on a legacy code which relies on Fixtures to load non UTF8 characters from yml files into database.

With rails lastest version, the yml must be utf-8 encoding, meaning that what Fixtures read in will be utf-8 encoding.

How to convert the following codes so that it will convert from utf-8 to non-utf8 and load into database (non-utf8 encoding of course).

class LoadUsersData < ActiveRecord::Migration
  def self.up
    down

    directory = File.join(File.dirname(__FILE__))
    Fixtures.create_fixtures(directory, "users")
  end
  def self.down
    User.delete_all
  end
end

where users.yml contains data in utf-8 format (have to).

Or is it possible to use .txt (can be in non-utf8 format) and load with Fixtures?

I am using oracle_enhanced, and I tried to change "encoding" to my database encoding in database.yml, but it seems that the conversion is not done automatically from utf-8 to my encoding (because the string length is different for these two encodings with utf-8 has more bytes, and the database returns that user_name is too long error).

回答1:

I solved this by

  1. add the following line in boot.rb

ENV['NLS_LANG'] ||= 'AMERICAN_AMERICA.JA16SJIS'

  1. convert all yml files to utf-8 format (Note that uses sjis formatted yml and ruby gem syck will load the yml but fixtures wont work even yml is loaded).