我在mysql下通过了以下测试(使用FactoryGirl):

  test "order by title" do
    @library = create(:drawing_library, title: 'Accessories')
    @drawing = create(:drawing, drawing_library: @library, title: 'Test Drawing')
    create(:drawing, drawing_library: @library, title: 'z')
    create(:drawing, drawing_library: @library, title: 'm')
    create(:drawing, drawing_library: @library, title: 'b')

    str = ''
    @library.drawings.each do |dwg|
      str += dwg.title
    end

    assert_equal 'bmTest Drawingz', str
  end

绘图模型为:
class Drawing < ActiveRecord::Base
  belongs_to :drawing_library
  default_scope order: :title
  ..
end

在postgresql下,此测试现在失败,原因是:
<"bmTest Drawingz"> expected but was
<"Test Drawingbmz">.

这似乎是因为“Test Drawing”中的T是大写的。如果我把它改成“测试图”,测试就通过了。
有没有办法使default_scope order不区分大小写?

最佳答案

您可以将默认范围更改为按小写标题排序:

default_scope order: 'lower(title)'

或者,如果你喜欢大喊大叫,你可以用大写来代替:
default_scope order: 'upper(title)'

不管您使用的是哪一个数据库,也不管它有什么配置设置(当然,除非您的数据库配置为使用有趣的排序规则),这一点都应该差不多。
如果希望此默认作用域参与联接,则可能需要包含表名。

10-07 13:11
查看更多