Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8503457
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T01:45:50+00:00 2026-06-11T01:45:50+00:00

Possible Duplicate: Rails ActiveRecord group_by & sum db results for use with Lazy HighCharts

  • 0

Possible Duplicate:
Rails ActiveRecord group_by & sum db results for use with Lazy HighCharts

I am completely new to RoR/Ruby and i am using Lazy High Charts gem to generate some purdy charts based on some database information.

I have tried the answers that were provided but i am still a bit confused as to how to do this..

I need to sum amount_used, and billed_amount and group by month/year (e.g; Aug/2012)

The end result will be something similar to a dual axis chart with two series "Amount Used", and "Cost".. This information is specific to a certain account_id.

enter image description here

Invoices table

+---------------+--------------+------+-----+---------+----------------+
| Field         | Type         | Null | Key | Default | Extra          |
+---------------+--------------+------+-----+---------+----------------+
| id            | int(11)      | NO   | PRI | NULL    | auto_increment |
| account_id    | int(11)      | YES  |     | NULL    |                |
| invoice_date  | varchar(255) | YES  |     | NULL    |                |
| amount_used   | float        | YES  |     | NULL    |                |
| billed_amount | float        | YES  |     | NULL    |                |
| comments      | text         | YES  |     | NULL    |                |
| created_at    | datetime     | NO   |     | NULL    |                |
| updated_at    | datetime     | NO   |     | NULL    |                |
+---------------+--------------+------+-----+---------+----------------+

Controller Chart Code

@account = Account.find(params[:id])
@invoices = Invoice.where("account_id = #{@account.id}").order("invoice_date DESC")

@h = LazyHighCharts::HighChart.new('area') do |f|
  f.options[:chart][:defaultSeriesType] = "area"
  #Sample dates right now, should be the grouped_by :invoice_date
  f.xAxis( :categories => ['May', 'Jun', 'Jul'] )
  f.yAxis([
    {
      :title => { :text => "Amount Used" }
    },
    {
      :title => { :text => "Cost" },
      :opposite => true
    }
  ])
  #Sample data right now, should be the summed amounts of the :amount_used correpsonding for each above grouped invoice_date
  f.series(:name => "Amount Used", :data => [100,300,500] )
  #Sample data right now, should be the summed amounts of the :billed_amount correpsonding for each above grouped invoice date
  f.series(:name => "Cost", :yAxis => 1, :data => [200,400,600] )
end 
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T01:45:51+00:00Added an answer on June 11, 2026 at 1:45 am

    The key is to use Enumerable#group_by to find all the rows with the same month and then add them together:

    require 'date'
    
    # Simulate rows from your DB
    Row = Struct.new(:date,:amount)
    rows = DATA.read.scan(/(\S+) - (\d+)/).map do |date,amount|
        Row.new( Date.strptime(date,'%m/%d/%y'), amount.to_i )
    end
    
    sum_by_month = rows.sort_by(&:date).group_by do |row|
        row.date.strftime('%b/%Y')
    end.map do |year_and_month,sub_rows|
        [ year_and_month, sub_rows.map(&:amount).inject(:+) ]
    end
    
    p sum_by_month
    #=> [
    #=>   ["Aug/2012", 22000],
    #=>   ["Sep/2012", 5000],
    #=>   ["Oct/2012", 76000]
    #=> ]
    
    __END__
    08/01/12 - 10000
    08/16/12 - 12000
    09/13/12 - 5000
    10/12/12 - 76000
    

    For your specific use case, you could use this like:

    <table><thead><tr><td></td>
      <%sum_by_month.each do |month,total|%>
        <th scope="col"><%=month%></th>
      <%end%>
    </thead><tbody>
      <tr><th>Usage:</th>
      <%sum_by_month.each do |month,total|%>
        <td><%=total%></td>
      <%end%></tr>
    </tbody></table>
    

    Alternatively, here’s a more direct approach (that I do not recommend):

    sum_by_month = {}
    last_month = nil
    total      = nil
    @invoices.each do |inv|
      month = inv.date.strftime('%b/%Y')
      unless last_month==month
        sum_by_month[month] = total if last_month
        last_month = month
        total      = 0
      end
      total += inv.amount
    end
    
    # Make sure to add in the very last month
    sum_by_month[month] = total if last_month
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Possible Duplicate: What does map(&:name) mean in Ruby? Ruby/Ruby on Rails ampersand colon shortcut
Possible Duplicate: Why does Ruby on Rails use 0.0.0.0:3000 instead of localhost:3000? I am
Possible Duplicate: Rails 3.0 & Ruby 1.9.2rc: Rake commands return 'already initialized constant' &
Possible Duplicate: Ruby On Rails 3 and Webrick issue $ rails server /Users/Vineeth/.rvm/gems/ruby-1.9.3-p194/gems/ruby-debug-base19-0.11.25/lib/ruby-debug-base.rb:1:in `require':
Possible Duplicate: Ruby 1.9.2 and Rails 3 cannot open rails console I have already
Possible Duplicate: Rails 3.1 and Ruby 1.9.3p125: ruby-debug19 still crashes with “Symbol not found:
Possible Duplicate: Can't convert String into integer in ruby/ruby-on-rails I'm running through a tutorial
Possible Duplicate: Is it possible to run Ruby on Rails with Ruby 1.9x? Browsing
Possible Duplicate: Ruby Refuses to Divide Correctly I am using Ruby on Rails 3.2.2
Possible Duplicate: What IDE / Editor do you use for Ruby on Linux? what

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.