Reed G. Law
Reed G. Law

Reputation: 3945

Rails find and sort using natural sort order collation

I want to return a paginated list of countries with Åland coming after Azerbaijan instead of after Zimbabwe. In other words, I want to ignore special characters and simply treat an "Å" as an "A" and the "ô" in Côte d'Ivoire as a regular "o". Is there a Rails method or gem to do this or do I need to execute some kind of custom SQL (and if so, what kind)?

Upvotes: 1

Views: 860

Answers (1)

Yannis
Yannis

Reputation: 5426

Look at How do I replace accented Latin characters in Ruby?.

You should be able to sort the countries by their normalized names.

Something like:

@countries.sort{|x,y| x.name.chars.normalize(:kd).gsub(/[^\x00-\x7F]/n,'').downcase.to_s <=> y.name.chars.normalize(:kd).gsub(/[^\x00-\x7F]/n,'').downcase.to_s}

Upvotes: 1

Related Questions