Skip to content
Advertisement

Ruby on Rails iterate through column efficiently

Hello My goal is to create a sum total of the values in ‘group_hits_per_iteration’ for each unique value in the ‘iteration column’ which will then be graphed using chartkick.

For example, for iteration 300 I would sum together 34,24,63,22,1,15 for a total of 159, then repeat for each unique entry.

The code I’ve included below does work and generates the required output but it’s slow and gets slower the more data is read into the database.

It creates a hash that is fed into chartkick.

I’m looking for other ways to approach this, I was thinking of having SQL do the heavy lifting and not do the calculations in rails but not really sure how to approach that.

Thanks for the help.

Advertisement

Answer

If you want to get just the sums for every iteration, following code should work:

In this case all the hard work is done by the database, you can just read the results in your ruby code.

Note: In your code you are taking first created_at for every iteration, I took the lowest date

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement