UTF-8错误的字节序列错误将文本插入数据库

时间:2017-05-02 07:34:06

标签: ruby-on-rails ruby utf-8 nokogiri

我正在尝试为我的富文本实现vignere密码。我正在使用Nokogiri来提取节点的innerHTML并在其上实现密码。

我的模特是:

# Entry.rb
class Entry < ApplicationRecord
  include EntriesHelper
  before_save :encode_content
  validates :content, presence: true

  def encode_content
    html_content=Nokogiri::HTML(self.content)
    nodes=html_content.css('p')
    nodes.each do |node|
      child=[]
      node.traverse{|n| child << n}
      text=child.first.text
      encoded_text=vignere_encoding(text)
      child.first.content=encoded_text
      puts child,encoded_text
    end
    modified_html=html_content.to_html
    self.content=modified_html.split("body>")[1][1..-4]
    save!
  end
end

辅助功能是:

#entries_helper.rb
module EntriesHelper
  def passphrase
    'cipher'.upcase
  end

  def coding(phrase)
    codes=Array.new(phrase.length)
    for i in 0...phrase.length
      codes[i]=phrase[i].ord-'A'.ord
    end
    codes
  end

  def vignere_encoding(input_str)
    stringish=input_str
    phrase=passphrase
    if not phrase
      return
    end
    code=coding(phrase)
    counter=0
    code_len=code.length
    for i in 0...stringish.length
      if counter>=code_len
        counter%=code_len
      end
      stringish[i]=(stringish[i].ord+code[counter]).chr
      counter+=1
    end
    return stringish
  end
end

一切都很好。 Vignere_encoding函数正确返回编码的字符串,而我正在尝试将数据保存到我正在获取的数据库

Invalid byte Sequence in UTF-8

有人可以告诉我如何实现这个吗?

1 个答案:

答案 0 :(得分:0)

尝试在entry.rb

之上添加此行

# encoding: UTF-8

我怀疑是在分割后内容得到保存