【问题标题】:ActiveRecord Query Failing For Name Containing Accented Characters包含重音字符的名称的 ActiveRecord 查询失败
【发布时间】:2013-09-18 12:14:26
【问题描述】:

我有一个使用 Postgres 的 Rails 应用程序。我有一个具有name 属性的Document 模型。某些名称包含重音字符。几个示例名称:

Condições Para Aplicação Da Lei

考虑介绍

我正在使用以下方法查询具有特定名称的模型:

document = Document.where(name: "Example Document Name").first

只要名称不包含特殊字符,就可以正常工作,但是只要我使用包含任何重音字符的名称,查询就会返回 nil。

$ Document.all
$ #<Document id: 1, name: "Foo" ... >
$ #<Document id: 1, name: "Considerações Introdutórias" ... >
$ Document.where(name: "Foo").first
$ #<Document id: 1, name: "Foo" ... > 
$ Document.where(name: "Considerações Introdutórias").first
$ # nil

为什么当名称包含特殊字符时此查询会失败?

在我的config/application.rb:

config.encoding = "utf-8"

在我的 `config/database.yml' 中:

encoding: utf8

【问题讨论】:

    标签: ruby-on-rails-3 postgresql activerecord unicode special-characters


    【解决方案1】:

    检查您的 utf 配置。 config.encoding = "utf-8"

    在 database.yml 中检查 encoding: utf8。

    查看这些问题

    Add "# coding: utf-8" to all files

    Set global default encoding for ruby 1.9

    【讨论】:

    • 谢谢。很好的建议(使用设置更新问题),但问题出在其他地方。
    【解决方案2】:

    原来问题不在于 Rails,而在于 OSX。相同的字符有不同的表示方式;可以作为单个符号,也可以分解为多个组件。两个版本在终端中显示相同,但​​将名称复制到纯文本文件中,您会看到不同之处:

    作曲:

    Considerações Introdutórias
    

    分解(我只能通过在分解字符周围添加空格来让分解版本显示在这里):

    Condic ̧ o ̃ es Para Aplicac ̧ a ̃ o Da Lei
    

    为了解决不匹配问题,我使用Unicode Utils 组合文件名,然后将它们添加到数据库中,然后再使用它们进行搜索:

    require "unicode_utils/nfc"
    
    ...
    
    filename = UnicodeUtils.nfc(filename)
    

    【讨论】:

      猜你喜欢
      • 2011-12-14
      • 1970-01-01
      • 2013-05-26
      • 1970-01-01
      • 2014-01-28
      • 2014-04-21
      • 1970-01-01
      • 2022-01-17
      相关资源
      最近更新 更多