【问题标题】:Rails isn't sorting child elements by (cyrillic) alphabetRails 不按(西里尔文)字母对子元素进行排序
【发布时间】:2017-12-26 13:32:58
【问题描述】:

无论我尝试什么,我都无法按标题进行排序。这是电流输出 - http://take.ms/M3W2Z,基本上是 A 在 N 之后,B 在 A 和 N 之后等等等等。

我的模型:

class Manufacturer < ApplicationRecord
  has_many :products
end

class Product < ApplicationRecord
  belongs_to :manufacturer
  scope :by_alphabet, -> { order('title DESC' ) }
end

我的看法:

-@manufacturer.products.by_alphabet.each do |product|
  =product.title

我试过scope :by_alphabet, -&gt; { order('products.title DESC') },但也没有用。

我是否遗漏了一些如此明显的东西?这只是一个简单的排序......还是关于西里尔字母的问题?我试图用俄语字母对一个简单的数组进行排序 - 它就像一个魅力。

【问题讨论】:

  • 表中字段的编码和排序规则是什么?
  • 如果我确实查对了:Manufacturer.find("moroshka-sladkaya-6m").products.first.title.encoding Manufacturer Load (0.2ms) SELECT "manufacturers".* FROM "manufacturers" WHERE "manufacturers"."slug" = $1 LIMIT $2 [["slug", "moroshka-sladkaya-6m"], ["LIMIT", 1]] Product Load (0.3ms) SELECT "products".* FROM "products" WHERE "products"."manufacturer_id" = $1 ORDER BY "products"."id" ASC LIMIT $2 [["manufacturer_id", 2], ["LIMIT", 1]] =&gt; #&lt;Encoding:UTF-8&gt;

标签: ruby-on-rails collation


【解决方案1】:

当排序由数据库完成时,如本例所示,您需要为查询(通过使用COLLATE 关键字)或在表上(通过模式)设置collation。默认排序规则不太可能是西里尔字母的正确排序规则。您需要检查哪些排序规则可用于您的数据库,但您可能会通过以下方式逃脱:

scope :by_alphabet, -> { order('title DESC COLLATE utf8_ru_ci' ) }

有关详细信息,请参阅您正在使用的数据库的文档,因为这可能因数据库而异。

【讨论】:

    【解决方案2】:

    @manufacturer.products.sort_by(&:title)

    【讨论】:

    • 我又回到了问题上,找到了我自己之前被删除的答案。不记得为什么会发生这种情况,但这又对我有用!
    • 我建议您在答案中添加更多解释。它已被删除,因为它被视为低质量/不是答案。人们不知道你是不是专家,所以他们会根据帖子的内容来判断。
    猜你喜欢
    • 2014-09-11
    • 2021-03-31
    • 2018-04-27
    • 2022-06-27
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多