Topic: .each do loop

This probably the wrong place for this question here goes anyways.
I have a view that needs to display around 5000 records at once. It takes around 20second to display. The do each loop is what is slow. Is that normal or is there a better way?

<% @bids.each do |bid| %>
  <tr align = center>
    <td width = "65"><small><%= link_to bid.bid_date, edit_bid_path(bid) %></small></td>
    <td width = "65"><small><%= bid.sold_date %></small></td>
    <td width = "100"><small><%= link_to bid.bid_number, edit_bid_path(bid) %></small></td>
    <td width = "100"><small><%= link_to bid.job_name, edit_bid_path(bid) %></small></td>
    <td width = "70"><small><%= bid.job_location %></small></td>
    <td width = "65"><small><%= number_to_currency(bid.quote_amount, :precision => 0) %></small></td>
    <td width = "65"><small><%= number_to_currency(bid.awarded_amount, :precision => 0) %></small></td>
    <td><small><%= bid.budget %></small></td>
    <td><small><%= bid.completion_date %></small></td>
    <td><small><%= bid.hardware_mfg %></small></td>
    <td><small><%= bid.markup %>%</small></td>
    <td><small><%= bid.gc_bid_list %></small></td>
    <td><small><%= bid.gcontractor.successful_gc %></small></td>
    <td align="center"><small><%= bid.bid_priority %></small></td>
    <td><small><%= bid.bid_comments %></small></td>
    <td><small><%= bid.job_info %></small></td>
    <td><small><%= bid.div10 %></small></td>
    <td><small><%= bid.estimator.first_name %> <%= bid.estimator.last_name %></small></td>
    <td><small><%= bid.companydivision.city_name %></small></td>
    <td><small><%= link_to 'Edit', edit_bid_path(bid) %></small></td>
    <td><small><%= link_to 'Destroy', bid, confirm: 'Are you sure?', method: :delete %></small></td>
    <td><small><%= link_to 'Show', bid %></small></td>

  </tr>
<% end %>

Last edited by lost (2012-06-08 18:21:57)

Re: .each do loop

Try to use 'find_each' method:

find_each(options = {})

Yields each record that was found by the find options. The find is performed by #find_in_batches with a batch size of 1000 (or as specified by the :batch_size option).

Example:

Person.where("age > 21").find_each do |person|
  person.party_all_night!
end

Note: 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.

Or just use one of pagination gems (Kaminari, will_paginate) which will do the job. Anyway, you are not going to display all the 5000 records on one page, right?

Last edited by Javix (2012-06-10 07:51:46)

Re: .each do loop

Anyway, you are not going to display all the 5000 records on one page, right?

Um well currently the user want this view to show all bids for the year on one page. Most of the time they only need one month or less. Also 5000 was a little high but not by much.