![](/img/trans.png)
[英]Error 'incompatible character encodings: ASCII-8BIT and UTF-8' due to 8-bit encoding of cookies (Rails 3 and Ruby 1.9)
[英]Move data across database with different encoding in ruby 1.9: “Encoding::CompatibilityError: incompatible character encodings: UTF-8 and ISO-8859-1”
我已經在ruby 1.9.3 / rails 3.1.0中編寫了一個應用程序,它可以將mysql作為數據庫,將utf8作為所有內容的編碼。 現在,我還必須在使用latin1作為編碼的舊數據庫中編寫此新應用程序的一些數據。 這是我的數據庫設置
# database.yml
development:
adapter: sqlite3
encoding: utf8
production:
adapter: mysql2
encoding: utf8
# other params
legacy:
adapter: mysql2
encoding: latin1
這些是我的模型(的簡化版本)
class Message < ActiveRecord::Base
attr_accessible :title, :content
def legacy_save
LegacyMessage.create!(title: title, content: content)
end
end
class LegacyMessage < ActiveRecord::Base
estabilish_connection 'legacy' # actually I'm using octopus gem to do this connection
end
當我在Message對象上調用legacy_save方法時,會發生以下兩種情況:僅包含ascii字符的消息被正確保存,或者包含非ascii字符的消息被引發異常。 我正在嘗試使此代碼正常工作,但是沒有運氣。
我得到的例外是
Encoding::CompatibilityError: incompatible character encodings: UTF-8 and ISO-8859-1
我已經嘗試過使用字符串類的編碼方法,如以下代碼所示,但是沒有運氣。
def legacy_save
LegacyMessage.create!(title: title.encode('ISO-8859-1'),
content: content.encode('ISO-8859-1')
)
end
有什么提示嗎?
調用encode()
會將文本從一種字符編碼轉碼為另一種字符編碼。 如果title
或content
包含無法編碼為ISO-8859-1的字符,則Ruby將引發此異常。
我的答案假設您的LegacyMessage.create!
引發了Encoding::CompatibilityError
異常LegacyMessage.create!
線。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.