Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveAdmin how to get sum from column

I have a situation where I'd like to get the sum of one column and display it

e.g in activeadmin

ActiveAdmin.register Expense do    
   index do       

    column :amount 
    column :details
    column :created_at

    default_actions
  end         
end

I need to sum the amount column and show it. Also I can't figure out where to show the Total Sum, maybe the sidebar? If the results are filtered then the sum has to change accordingly to results shown.

like image 992
Jawad Avatar asked Dec 15 '22 20:12

Jawad


1 Answers

You can avoid having to count up with a running total, by simply accessing the underlying collection which will take into account currently applied filters/scopes, and use reduce(:+) to perform the sum:

ActiveAdmin.register Expense do    
   index do       
    column :amount 
    column :details
    column :created_at

    default_actions

    div class: "panel" do
      h3 "Total amount: #{collection.pluck(:amount).reduce(:+)}"
    end
  end         
end
like image 74
rlarcombe Avatar answered Dec 31 '22 20:12

rlarcombe