user1203891
user1203891

Reputation: 27

Rails 3 displaying count inside a loop

The following displays a list of documents grouped by subject and the name of each document is the name of the packet type. How do I display the the count for each packet type name? so for example if there are two documents for the first subject and their packet type names are 'class' how do I display 'class 1 of 2' and class 2 of 2' next to the packet type name?

controller:

class DevelopController < ApplicationController

    def index
        list
            render('list')
    end

    def list
            @subjects = Subject.includes(:documents => :packet_type)            

    end

end

view:

<ol>
    <% @subjects.each do |subject| %>
    <li><%= subject.subject_name %>
        <ul>
            <% subject.documents.each do |document| %>
          <li><%= document.packet_type.name %></li>
    </li>
           <% end %> 
       </ul>
   <% end %>
</ol>

Upvotes: 1

Views: 1490

Answers (1)

ksol
ksol

Reputation: 12275

You can get the total count with .size or .count. To get the current index, you can use each_with_index instead of each. And here on a silver plate : http://apidock.com/ruby/Enumerable/each_with_index :)

Upvotes: 2

Related Questions