如何使用 postgresql 在 Rails 中执行不区分大小写的顺序

发布于 2024-09-04 09:08:41 字数 250 浏览 2 评论 0原文

我正在将我的开发环境从 sqlite3 切换到 postgresql 8.4,并且还有最后一个障碍。

在我的原文中,我在辅助方法中有以下行;

result = Users.find(:all, :order => "name collate NOCASE")

这提供了一个非常好的不区分大小写的搜索。我无法为 postgresql 复制这个。应该很容易 - 有什么想法吗?

谢谢。

I am in the process of switching my development environment from sqlite3 to postgresql 8.4 and have one last hurdle.

In my original I had the following line in a helper method;

result = Users.find(:all, :order => "name collate NOCASE")

which provided a very nice case-insensitive search. I can't replicate this for postgresql. Should be easy - any ideas?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

同展鸳鸯锦 2024-09-11 09:08:41
result = Users.find(:all, :order => "LOWER(name)")

从布拉德和弗兰克那里吸取一些教训。

result = Users.find(:all, :order => "LOWER(name)")

To take a little bit from both Brad and Frank.

旧时光的容颜 2024-09-11 09:08:41

LanecH 的答案适用于 Rails 3+(包括 Rails 4 和 5):

users = User.order('LOWER(name)')

或者创建一个可以重用的命名范围:

class User < ActiveRecord::Base
  scope :order_by_name, -> { order('LOWER(name)') }
end

users = User.order_by_name

LanecH's answer adapted for Rails 3+ (including Rails 4 and 5):

users = User.order('LOWER(name)')

Or create a named scope you can reuse:

class User < ActiveRecord::Base
  scope :order_by_name, -> { order('LOWER(name)') }
end

users = User.order_by_name
不必了 2024-09-11 09:08:41

现在,在 Rails 5.2 中,如果使用已接受的答案,您可能会收到警告。

弃用警告:危险的查询方法(其参数的方法
用作原始 SQL)使用非属性参数调用:“LOWER(?)
ASC”。

替代方案可以依赖 Arel(它现在已合并到 Rails 中):

results = User.order(User.arel_table['name'].lower.asc)
# results.to_sql == "SELECT \"users\".* FROM \"users\" ORDER BY LOWER(\"users\".\"name\") ASC" 

Now with Rails 5.2 you probably will get a warning if using the accepted answer.

DEPRECATION WARNING: Dangerous query method (method whose arguments
are used as raw SQL) called with non-attribute argument(s): "LOWER(?)
ASC".

An alternative could be relying on Arel (it's merged now into Rails):

results = User.order(User.arel_table['name'].lower.asc)
# results.to_sql == "SELECT \"users\".* FROM \"users\" ORDER BY LOWER(\"users\".\"name\") ASC" 
未蓝澄海的烟 2024-09-11 09:08:41

您是否考虑过将列存储为 citext 类型?据我了解,它实际上只是内部化了对 lower() 的调用。之后这对您来说将是自动的。如果有时您需要区分大小写的搜索,但这可能不是最好的主意。

Have you considered storing your column as citext type? It really just internalizes the call to lower() as I understand it. It would be automatic for you afterwards. If there are times you need a case sensitive search, this may not be the best idea though.

睫毛上残留的泪 2024-09-11 09:08:41

在 SQL 中,您可以使用 ORDER BY LOWER(columnname),不知道如何在 Ruby 中执行此操作。功能索引(也在 LOWER(columnname) 上)将有助于加快速度。

IN SQL you could use ORDER BY LOWER(columnname), no idea how to do it in Ruby. A functional index (also on LOWER(columnname) ) will help to speed things up.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文