M
M
Maxim Grechushnikov2014-11-19 02:10:20
Ruby on Rails
Maxim Grechushnikov, 2014-11-19 02:10:20

Rails: How to ungroup data?

Such a task. The database contains a list of cities.
It is necessary to display the list in such a way that cities with the same first letter in the name are collected in separate divs,
for example ,
div
arkhangelsk, armavir, almaty
div
moscow
div
peter
at the moment there is only enough knowledge for city.all
I promise to learn quickly

Answer the question

In order to leave comments, you need to log in

3 answer(s)
_
_ _, 2014-11-19
@maxyc_webber

Know your standard library
The group_by method of the Enumerable module

['Test','Bla','Test2'].group_by{|str| str[0]}
 => {"T"=>["Test", "Test2"], "B"=>["Bla"]}

For your case something like
<% @cities_grouped.each do |letter, group| %>
    <div>
        <% @group.each do |city| %>
            <%= city.name %>      
        <% end %> 
    </div>
<% end %>

S
Sergey Krasnodemsky, 2014-11-19
@Prognosticator

search by first letter
it's better to select all the cities and do the sorting using js
, I think you don't have 100 thousand of them, because why are there 33 requests on the backend

P
Philipp, 2014-11-19
@zoonman

I think it makes the most sense to do this in the view.
Approximately so (did not check)

<% cityLetter = '' %>
<% @cities.each do |city| %>
  
        <% if (cityLetter != city.name[0])
             cityLetter = city.name[0]
        %>
          </div><div>
        <% end %>

        <%= city.name %>

<% end %>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question