5
@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.

2 Answers 2

11

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>
Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

This works, but in_groups_of is probably more appropriate for this task. From the API (you link to): This method is only intended to use for batch processing of large amounts of records that wouldn’t fit in memory all at once. If you just need to loop over less than 1000 records, it’s probably better just to use the regular find methods.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.