Reputation: 2889
This is my code:
<table class="video_table">
<% count = 0 %>
<tr>
<% @f_videos.each do |f_video| %>
<td><%= f_video.name %></td>
<td><%= f_video.date_added %></td>
<td><%= f_video.views %></td>
<% count +=1 %>
<% if count == 4 %>
</tr>
<% end %>
<% end %>
</table>
at each 4 videos placed I want the table to switch row. So I implemented a counter. But it is not working. Any ideas?
Upvotes: 1
Views: 487
Reputation: 11198
Another solution:
<table class="video_table">
<% @f_videos.in_groups_of(4) do |group| %>
<tr>
<% group.each do |f_video| %>
<td><%= f_video.name %></td>
<td><%= f_video.date_added %></td>
<td><%= f_video.views %></td>
<% end %>
</tr>
<% end %>
</table>
in_groups_of
has the added value/advantage that, when needed, it allows for padding any remaining slots with eg ' '
, which can be very useful. See the docs.
Upvotes: 1
Reputation: 77778
Your count will only be set to 4 once.
Instead of if count == 4
use if count % 4 == 0
This will repeat the </tr>
for each multiple of 4
Alternatively, you could skip using the count variable and use each_with_index
to get the same result
<table class="video_table">
<% @f_videos.each_with_index do |f_video, i| %>
<tr>
<td><%= f_video.name %></td>
<td><%= f_video.date_added %></td>
<td><%= f_video.views %></td>
<% if (i+1) % 4 == 0 %>
</tr>
<% end %>
<% end %>
</table>
Even better! each_slice
<table class="video_table">
<% @f_videos.each_slice(4).to_a do |slice| %>
<tr>
<% slice.each do |f_video| %>
<td><%= f_video.name %></td>
<td><%= f_video.date_added %></td>
<td><%= f_video.views %></td>
<% end %>
</tr>
<% end %>
</table>
Upvotes: 2