Crazy Coders
Crazy Coders

Reputation: 133

Rails - Sort items and change title according to sorting

I have a table which has animals. I have just 2 species: dog and cat.

I want to sort items in view and add a h1 (like: Cats Names , Dogs Names ) when animal species come to the other one. I can do this by putting dogs(@dogs) and cats(@cats) to different variables in the controller but I want to achieve it in view if it is possible.

I can sort animals in my view like:

 <% @animals.sort_by(&:specy).each do |animal| %>
       // Here I need to add a h1 when species change
      <%= animal[:name] %>
  <% end %>

How I want to sort and show in my view is:

Cat Names
Bella
Kitty
Lilt
Dog Names
Charlie
Luna
Max

Upvotes: 0

Views: 56

Answers (2)

Monith Shah
Monith Shah

Reputation: 344

You can use group_by method to group an collection based on an attribute.

<% @animals.order(:specy).group_by(&:specy).each do |animal_species, animals| %>
  <h1><%= animal_species %> Names</h1>
  <% animals.each do |animal %>
    <%= animal.name %>
  <% end %>
<% end %>

Source https://apidock.com/ruby/Enumerable/group_by

You might also want to use sql group along with GROUP_CONCAT function to achieve better performance.

Upvotes: 0

edariedl
edariedl

Reputation: 3352

sometimes it is better to use two queries, you will probably save yourself a nice chunk of code and it will be nicer and easier to read. But if you really want to solve it in the views, you can do something like this:

In your controller

# other conditions are omitted
@animals = Animal.order(:specy)

In the view

<% last_specy = nil %>
<% @animals.each do |animal| %>
  <% if last_specy != animal.specy %>
    <h1><%= animal.specy %> names</h1>
    <% last_specy = animal.specy %>
  <% end %>

  <%= animal[:name] %>
<% end %>

Upvotes: 1

Related Questions