I'm trying to display a list of titles from my database in alphabetical order and also in blocks.
I want to output the letter and then include all titles that start with that letter. For example:
I know that I can order my results using .order('title'), but I'm not sure what the best way to write the display code is?
titles.group_by {|word| word[0].upcase }
So, then if:
titles = ['Apple', 'anothersomething', 'Bob']
Then:
grouped_titles = titles.group_by {|word| word[0].upcase }
=> {"A"=>["Apple", "anothersomething"], "B"=>["Bob"]}
In order to be certain about the ordering, you can sort the resulting Hash, which converts it into an array:
grouped_titles = grouped_titles.sort_by{|k, v| k}
=> [["A", ["Apple", "anothersomething"]], ["B", ["Bob"]]]
Then you can iterate over the resulting array.
<% grouped_titles.each do |initial_letter, titles| %>
-display stuff here-
<% end %>
Note that this is grouping in Ruby, rather than in the database (which would be done by using a .group
method on the relation), but if you were already displaying all the data in the page, this method should be fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With