How to do case-insensitive order in Rails with postgresql

梦想与她 提交于 2019-12-20 10:26:44

问题


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.


回答1:


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

To take a little bit from both Brad and Frank.




回答2:


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



回答3:


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" 



回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/2983687/how-to-do-case-insensitive-order-in-rails-with-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!