will_paginate dropping "sum" after first page
I am using will_paginate which works like a charm for breaking up my results into many pages. But on any page but the first one, my 'sum' method returns 0.
My view has two tables in it. The first is summary information over the entire collection and the second is the paginated collection. Page 1 of my collection shows everything perfect. Page >= 2 turns the 'sum' to 0 yet .count still works.
My controller:
def donations_by_season
@season_name = params[:season_name]
@donations = Donation.by_season(@season_name).paginate :page=>params[:page], :order=>'created_at desc', :per_page => 25
@valid_seasons = Donation.select(:season).group(:season)
end
My Partial has these values in the top table:
<td> <%= number_to_currency @donations.sum(:amount) %>&l开发者_JAVA技巧t;/td>
<td><%= @donations.count %></td>
And these in the lower:
<% @donations.each do |donation| %>
<tr class="<%= cycle("odd", "even", :name => "row_class") %> ">
<td><%= number_to_currency(donation.amount) %></td>
<td><%= donation.iho_full %></td>
<td><%= donation.box_code %></td>
<td><%= donation.list_name %></td>
</tr>
<% end %>
</table>
<p><%= will_paginate @donations %></p>
On page one, number_to_currency @donations.sum(:amount)
and @donations.count
are accurate. After page one, the .sum turns to 0 but the .count remains the same. How do I get the .sum to work as well?
I believe will_paginate is overriding the relation method "count".
If you take a look at the relation returned by the paginate method, it doesn't contain the elements that it says its counting.
The same for sum. It must be overwritting it, because it does not reflect what the true collection is returning.
If you refactor your code, to use:
@all_donations = Donation.by_season(@season_name)
@donations = @all_donations.paginate :page=>params[:page], :order=>'created_at desc', :per_page => 25
And use @all_donations, to get the count and sum metrics, it should work.
精彩评论