Case Insensitive default_scope:order?

时间:2012-08-21 02:37:23

标签: ruby-on-rails ruby postgresql activerecord rails-activerecord

我在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为大写。如果我将其更改为'test Drawing',则测试通过。

有没有办法让default_scope order不区分大小写?

1 个答案:

答案 0 :(得分:4)

您可以通过小写标题更改默认范围:

default_scope order: 'lower(title)'

或者,如果你喜欢大喊大叫,你可以改用大写字母:

default_scope order: 'upper(title)'

无论您使用的是哪个数据库或它具有哪些配置设置,这都应该完全相同(除非您的数据库配置为使用有趣的排序规则)。

如果您希望此默认范围参与连接,则可能需要包含表名。