Cumulative Sum with will_paginate and activerecord

Hi everyone,

I am trying to a cumulative sum on each page using will_paginate. I don't want the sum of each page, but the cumulative sum. Here is an example:

on Page 1 I have:

AR has a sum function.

Hi Radhames,

I am aware of the sum function, but it does not do cumulative sum on its own. I know how to do it using recursive queries or stored procedures, but my question is how to deal with that using will_paginate.

I will try to read the api and see if I can tweak it.

Best Regards,

Fidel.

> AR has a sum function.

Hi Radhames,

I am aware of the sum function, but it does not do cumulative sum on its own. I know how to do it using recursive queries or stored procedures, but my question is how to deal with that using will_paginate.

I will try to read the api and see if I can tweak it.

The sum function takes conditions just like find does. Depending on what you are sorting on you should be able to construct the relevant conditions from the items will paginate fetches for you.

Fred

For the problem in question that does not work. I read through the documentation and found out that I could paginate_by_sql, which is what I really needed.

Thanks a lot!!!!

Regards,

Fidel.

add a hidden field with in them it will make the params create an array and put the ids of the paged record in them , then pass the array in a find and call sum on it.

f.hidden :things, thing.id

then

find(params[:things])

Or include a separate variable with the sum you want to include in addition to the will_paginate variable.

@figures = Figures.paginate... @figure_sum = Figures.sum(...

That is quite a lot of work. In sql I can do this "select date, in, out, @total := @total + in - out as balance from mytable". My problem (or maybe I was being lazy) was more with will_paginate. After reading the documentation I found the paginate_by_sql method, which was what I was looking for.

The problem I am trying to solve cannot be resolved using ActiveRecord's default methods. I need to use sql, because it is not possible to replicate that in plain AR, or maybe it is quite a lot of work. This is one of those cases where you better use sql than AR built-in methods. The sum method would never solve this problem alone, because I need the cumulative sum on each row and in the last page the running total as well.

so, using the paginate_by_sql is the cleanest solution to my problem. I only have to pass the value of @total to each page as a hidden param so that it can continue with the sum on the next page.

Best Regards,

Fidel.

This will only give me the running total per page, not the cumulative sum on a row by row basis. @figure_sum is similar to what I am using to pass the running total up to the current page into the next page.

Thanks for the reply though.

Regards,

Fidel.