4

I have a table with two columns level, and slot. each level can have many slots, but I have made one table that models this case. example

level    |   slot
1        |   1
1        |   2
1        |   2
2        |   1
2        |   2
2        |   2

and in my erb template I want to make a table that will model this case by making something like a grid. The issue so far, is I want somethink like two loops to handle this situation. for each level, I get the number of slots and display them. the provided each loop is not helping. I am thinking of creating a variable that will keep track of the level variable, and when it changes, I call the inner loop. but this does not loop efficient to me.

I am thinking also of creating a json object and make the slots apeats as an array inside the level variable, but I have no idea from where to start this.

or is there a way to write a while loop in the erb template?

anyavacy
  • 1,618
  • 5
  • 21
  • 43

3 Answers3

5

You can write a loop in ruby (erb) this way:

<% loop do %>
  ...
  <% break if <condition> %>
<% end %>

See Is there a "do ... while" loop in Ruby?

Community
  • 1
  • 1
mgrim
  • 1,284
  • 12
  • 16
  • Just a note that loops in ruby are to be avoided because they leak their variables outside of their scope, unlike using enumerators. – Mohamad Apr 19 '15 at 14:44
4

ERB is just ruby

<% @collection.each do |value| %>
  <%= value %>
<% end %>
CuriousMind
  • 33,537
  • 28
  • 98
  • 137
  • yes I know, that, but i want something like another loop while inside that. with that, I can do something like while(level = 1){//do something here} – anyavacy Apr 19 '15 at 14:37
2

It can still be one table. I would create a variable called @slots in your action, and call .each on it in your erb view like so:

<% @slots.each do |slot| %>
 <% if ...  %>
  <div class="left-column">
    <%= slot.level %>
  </div>
  <div class="right-column">
    <%= slot.id %> <!-- or whatever var you you want --> 
  </div>
 <% else %>

 ...

 <% end %>
<% end %>

This way each new slot will be automatically added to the collection, and you don't need to worry about changes to the level

dimitry_n
  • 2,939
  • 1
  • 30
  • 53