Search code examples
ruby-on-railsrubyalphabetical

Rails - How to create alphabetical system?


I am getting data from my mySQL database with Ruby on Rails like that:

def all_specs
   Specialization.order("title ASC").all;
end

Now, I would like to sort this data in the view file like that:

 <div class="nav-column">
   <h3>A</h3>
    <ul class="submenu">
        <li><a href="#">All data that has title that starts with A</a></li>
    </ul>
</div>   

 <div class="nav-column">
   <h3>A</h3>
    <ul class="submenu">
        <li><a href="#">All data that has title that starts with B</a></li>
    </ul>
</div>   

and so on from A-Z

How can I achieve that ?


Solution

  • You could group the data:

    specs = Specialization.order("title ASC")
    specs_by_first_letter = specs.group_by { |spec| spec.title[0] }
    

    This returns a hash like:

    {
      "A" => [<Specialization title:"A...">, <Specialization title:"A...">],
      "B" => [<Specialization title:"B...">, <Specialization title:"B...">],
      ...
      "Z" => [<Specialization title:"Z...">, <Specialization title:"Z...">]
    }
    

    Looping through this hash should be quite easy. Note that some letters could be missing.