Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails Splitting or Slicing list into columns

@locations = Location.all #current listing all

@locations = Location.slice(5) or Location.split(5)

With Ruby I'm trying to split my list into 4 columns, limiting each column to 5 each; however neither slicing or splitting seems to work. Any idea of what I might be doing wrong? any help is greatly appreciated.

like image 295
nil Avatar asked May 04 '13 15:05

nil


2 Answers

You probably want to use in_groups_of:

http://railscasts.com/episodes/28-in-groups-of

Here's Ryan Bates' example usage from that railscast:

<table>
<% @tasks.in_groups_of(4, false) do |row_tasks| %>
  <tr>
    <% for task in row_tasks %>
      <td><%= task.name %></td>
    <% end %>
  </tr>
<% end %>
</table>
like image 55
Shawn Balestracci Avatar answered Oct 30 '22 09:10

Shawn Balestracci


Would something like the following suit your purposes?

Location.find_in_batches(batch_size: 5) do |group|
  # code to work with these 5 elements
end

find_in_batches yields each batch of records that was found by the find options as an array.

like image 33
Luís Ramalho Avatar answered Oct 30 '22 09:10

Luís Ramalho