ruby on rails - Donations over past 24 months with keys and sums -


having pulled donations past 2 years, i'm trying derive sum of donations per month, storing keys (each month) , values (the sum of donations each month) in array of hashes. keys numbers 1 24 (1 being 2 years ago , 24 being month) , if there no donations given month, value 0 month. how array of hashes in ruby/rails?

this variable donations in it.

donations = gift.where(:date => (date.today - 2.years)..date.today) 

the following gives hash, keys '2013/09" , etc...

 monthly_donations = {}  date = time.now  while date > 2.years.ago      range = date.beginning_of_month..date.end_of_month    monthly_donations[ "{#date.year}/#{date.month}" ] = giftl.sum(:column, :conditions => {created_at >= range})     date -= 30.days  end 

to select records in time-span, should enough:

 donations = gift.where("date >= #{2.years.ago}")  

you can this:

 donations = gift.where("date >= :start_date , date <= :end_date",                          {start_date: 2.years.ago, end_date: time.now} ) 

see also: 2.2.1 "placeholder conditions" http://guides.rubyonrails.org/active_record_querying.html

to sum-up column in database record, can this:

 sum = gift.sum(:column , :conditions => {created_at >= 2.years.ago}) 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -