I am trying to create a glossary of terms ordered alphabetically like this example:
-A-
Alpha
ATM
-B-
Beta
...
I have no problem to group terms by letter but I wonder how I can manage symbol and digits in order to group them through a # symbol
-#-
52 weeks low
@test
I figured out to add a column in my Term tab开发者_开发技巧le where I specify the first letter (in the symbol case I would select a "#" in a select box for example) but I would be pleased to know if there is a better way to achieve this without adding another field.
As info, here is my controller:
@terms = Term.all.group_by{|t| t.name[0]}
and my view:
<% @terms.keys.sort.each do |first_letter| %>
<%= first_letter %>
<% @terms[first_letter].each do |term| %>
<%= term.name %>
<% end %>
<% end %>
Thanks for your help!
You can do it like this, might be a performance hit, but gets the job done:
@terms = Term.all.group_by{|t| t.name[0].capitalize.match(/[A-Z]/) ? t.name[0].capitalize : "#" }
精彩评论