Splitting activerecord query results into two objects

Is there a rail-like way to split activerecord query results? For example, I did @results = Items.find (: all), but I want the top half of the elements from @results to appear in the line below <ul class="part1">, and the other half to be displayed in <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>

early!

+3
source share
2 answers

You can use the in_groups method from ActiveSupport:

@grouped_results = @results.in_groups(2)

and move on to @grouped_results[0]for part1 and @grouped_results[1]for part 2.

+7
source
@results[0...@results.size/2] #part1
@results[(@results.size/2)..-1] #part2
+1
source

Source: https://habr.com/ru/post/1712323/


All Articles