How to do case-insensitive order in Rails with postgresql How to do case-insensitive order in Rails with postgresql ruby ruby

How to do case-insensitive order in Rails with postgresql


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

To take a little bit from both Brad and Frank.


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" 


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)') }endusers = User.order_by_name