Skip to content

Instantly share code, notes, and snippets.

@nickhammond
Created November 19, 2011 01:00
Show Gist options
  • Save nickhammond/1378244 to your computer and use it in GitHub Desktop.
Save nickhammond/1378244 to your computer and use it in GitHub Desktop.
Order users by company name or last name
# This assumes you have the fields first_name, last_name and company_name on your model User.
#
# If there's a simpler way to do this please let me know. The issue was mostly with how MySQL
# sorts null values. If you have your order clause as "order by company_name, last_name" then
# columns with company_name that have null would be first which you don't want, you want it
# to use the value for last_name instead. You could also do this all in memory in Ruby but
# when you are also paginating it's easy enough to get your hands dirty with some SQL.
# app/models/user.rb
named_scope :sorted, :order => "sort_name, first_name ASC",
:select => "*, concat(ifnull(company_name,''), ifnull(last_name,'') as sort_name"
def sort_initial
"#{company_name}#{last_name}".strip.first.downcase
end
# app/controllers/users_controller.rb
def index
@users = User.sorted
end
# app/views/users/index.html.haml
- @users.group_by(&:sort_initial).each do |sort_initial, users|
%h2= sort_initial.first.capitalize
%ul
- users.each do |u|
%li= u.display_name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment