Unknown19 Unknown19 - 7 months ago 11
Ruby Question

How to create custom text to display questions

I'm displaying questions in my view like this:

<% @categories.each do |category| %>
<h1><%= category.name %></h1>
<% category.questions.each do |question| %>
<ul>
<li><%= link_to question.id, question_path %></li>
</ul>
<% end %>
<% end %>


I'm linking to the question's id but ids are different, like 4, 6, 25, 30.

But I need questions to start from 1 like this:

Category1
1 2 3 4 5 6 7


Category2
1 2 3 4 5 6 7


How do I create custom text for displaying questions like above?

Answer

You can use each_with_index to get the index of the question (with respect to the category):

<% category.questions.each_with_index do |question, i| %>
     <ul>
         <li><%= link_to (i + 1), question_path %></li>
     </ul>
<% end %>
Comments