Petr
October 17, 2006, 9:56am
1
Hi,
I’d like iterate through a model object(its an array object as you know)
in the view so that it displays 2 database table rows in one html table
row(in separate columns
) and then moves to display the next 2
database table rows in the next html table row.
Like this:
array[0]
array[1]
array[2]
array[3]
…
Im kinda clueless about this. Any ideas?
Thanks
Petr
Petr
October 17, 2006, 4:07pm
2
Thanks.
But, you forgot to mention how to bring that into html, so if you could
do that it would be great.
Thanks again,
Petr
Max M. wrote:
On 10/17/06, Petr [email protected] wrote:
Im kinda clueless about this. Any ideas?
Thanks
Petr
Either the rails only way:
some_array.in_groups_of(2)
which pads with nil, or the more ruby way:
require ‘enumerator’
some_array.slice(2)
Cheers,
Max
Petr
October 17, 2006, 10:43am
3
On 10/17/06, Petr [email protected] wrote:
Im kinda clueless about this. Any ideas?
Thanks
Petr
Either the rails only way:
some_array.in_groups_of(2)
which pads with nil, or the more ruby way:
require ‘enumerator’
some_array.slice(2)
Cheers,
Max
Petr
October 17, 2006, 4:32pm
4
I asked this yesterday in a post titled “Going through an array in
batches…”
Hope this helps:
#in_groups_of
Changeset 3726 adds two little methods to ActiveSupport: Enumerable#group_by and @ Array#[email protected] #group_by is for collecting an enumerable into sets, grouped by the result of a block. Useful, for example, for grouping records by date....
<% @products.in_groups_of (4) do |row| %>
<% row.each do |product| %>
<%= product.name %>
<% end %>
<% end -%>
Petr
October 19, 2006, 2:41am
5
On 10/18/06, Petr [email protected] wrote:
Thanks.
But, you forgot to mention how to bring that into html, so if you could
do that it would be great.
Thanks again,
Petr
Use in place of some_list.each. Instead of
<% for thing in list %>
… render stuff …
<% end %>
use
<% list.in_groups_of(2) do |two_things| %>
<%= two_things[0].some_attribute if two_things[0] %>
<%= two_things[1].some_attribute if two_things[1] %>
<% end %>
The nil check is necessary, as in_groups_of pads the last “row” with
nils if there are not enough elements in the list.
BTW, googling for “rails in_groups_of” would have gotten you there as
well…
Cheers,
Max