views:

70

answers:

2

Is there a rails-like way to divide results from an activerecord query? For example, I did @results = Items.find(:all), but I want the top half of items from @results to appear in a line item under <ul class="part1">, and the other half of them to appear under <ul class="part2">.

<ul class="part1">
    <li><a href="#">result["name"]</a></li>
</ul>

<ul class="part2">
    <li><a href="#">resultpart2["name"]</a></li>
</ul>

thanks in advanced!

+1  A: 
@results[[email protected]/2] #part1
@results[(@results.size/2)..-1] #part2
Ben Hughes
+4  A: 

You can use the in_groups method from ActiveSupport:

@grouped_results = @results.in_groups(2)

and iterate over @grouped_results[0] for part1 and @grouped_results[1] for part2.

Greg Campbell
+1 for in_groups. Also don't forget Array#from and Array#to.
Simone Carletti
Thanks, Greg! I knew there would be a rails-like way to do this. :)
Jess