Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 Listing ActiveRecord objects alphabetically

How can i create a queryset and view (@contacts in my situation) in Rails 3 to list ActiveRecord objects alphabetically?

I'm trying to do this implementation;

A -> Contacts starts with A

B -> Contacts starts with B etc.

Final look: http://jquerymobile.com/demos/1.0b1/#/demos/1.0b1/docs/lists/lists-divider.html

Thanks

like image 986
Harry Avatar asked Nov 30 '22 04:11

Harry


1 Answers

You have to do something like this:

@users = User.all.group_by{|u| u.name[0]}

In the view:

<% @users.keys.sort.each do |starting_letter| %>
  <%= starting_letter %>
  <% @users[starting_letter].each do |user| %>
    <%= user.name %>
  <% end %>
<% end %>
like image 123
Arun Kumar Arjunan Avatar answered Dec 07 '22 00:12

Arun Kumar Arjunan