Search code examples
ruby-on-railssortingmethodscollectionsmodels

Alphabetical Sort collection objects by custom model method


I have a method in my User model called display_name. In my controller I want to sort all the User objects by their display_name in alphabetical order. display_name returns a string, how do I do this?

User

  def display_name
      if !addressbook.b_company.nil?
        if addressbook.b_company.downcase[0..3] == "the "
                addressbook.b_company[4..-1]
        else
                addressbook.b_company
        end
      else
          "#{addressbook.b_lastname}, #{addressbook.b_firstname}"
      end
  end

Solution

  • Use sort_by and pass it your method:

    @users.sort_by(&:display_name).each do |user|
      # your code here
    end