rails count records
Let say i have the following car loop and i want to display 4 cars on one row and then create a new row etc.
<table>
<tr>
<% @cars.each do |ca开发者_开发知识库r| %>
<td><%= car.name %></td>
<% end %>
</tr>
</table>
So i looks like this:
car1 car2 car3 car4
car5 car6 car7 car8
car9 car10 ... ... ...
How do I do that?
<table>
<% @cars.each_slice(4) do |cars| %>
<tr>
<% cars.each do |car| %>
<td><%= car.name %></td>
<% end %>
</tr>
<% end %>
</table>
Adding a class to last td
in a row:
<table>
<% @cars.each_slice(4) do |cars| %>
<tr>
<% cars.each do |car| %>
<td <%= "class='my_class'" if car == cars.last %>>
<%= car.name %>
</td>
<% end %>
</tr>
<% end %>
</table>
You can take advantage of the each_slice method from Enumerable, an example like so:
[1,2,3,4,5,6,7,8,9,10].each_slice(4).to_a
#=> [1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]
So your code would be like:
<table>
<% @cars.each_slice(4) do |cars| %>
<tr>
<% cars.each do |c| %>
<td><%= c.name %></td>
<% end %>
</tr>
<% end %>
</table>
Point is, always check out the Enumerable page for things like this. Ruby provides amazing methods like this!
精彩评论