rico_mac
rico_mac

Reputation: 888

How to sort a list alphabetically in rails view

I am generating a list of centres, but because the centres are a child of borough, I was wondering how to sort the iteration alphabetically in the views.

My code looks like this

        <% boroughs.each do |borough|%>
          <% if borough.leisure_centres.any? %>
            <% borough.leisure_centres.each do |venue| %>
            <li class="sitemap-accordion">
              <%= link_to venue.title, '#', class: "trigger" %>
                <ul class="sitemap-accordion-child">
                  <li>
                    <%= link_to "Overview", centre_path(venue) %>
                  </li>
                  <li>
                    <%= link_to 'News', centre_news_index_path(venue) %>
                  </li>
                  <li>
                    <%= link_to 'Facilities', facilities_centre_path(venue) %>
                  </li>
                  <li>
                    <%= link_to 'Contact Us', new_centre_contact_form_path(venue) %>
                  </li>
                  <% unless venue.venue_hire_content.nil? %>
                    <li>
                      <%= link_to 'Hire', venue_hire_centre_path(venue) %>
                    </li>
                  <% end %>
                  <% unless venue.virtual_tour.nil? %>
                    <li>
                      <%= link_to 'Virtual Tour', tour_centre_path(venue) %>
                    </li>
                  <% end %>
                  <% unless venue.custom_pages.nil? %>
                    <% venue.custom_pages.each do |custom_page| %>
                      <li>
                        <%= link_to custom_page.title, centre_custom_page_path(centre_id: venue, id: custom_page.id) %>
                      </li>
                    <% end %>
                  <% end %>
                </ul>
              <% end %>
            </li>
          <% end %>
        <% end %>

I would like venue.title to be in alphabetical order, how do i do this?

Thanks

Upvotes: 1

Views: 3116

Answers (2)

j-dexx
j-dexx

Reputation: 10406

I would do

Rails 4

class Borough < ActiveRecord::Base
  has_many :leisure_centres, -> { order "title asc" }
end

Rails 3

class Borough < ActiveRecord::Base
  has_many :leisure_centres, :order => "title asc"
end

So you are sorting via SQL not ruby.

Upvotes: 2

Santhosh
Santhosh

Reputation: 29094

You can pass a block to sort_by method like this.

<% borough.leisure_centres.sort_by(&:title).each do |venue| %>

Upvotes: 3

Related Questions