Search code examples
ruby-on-railsruby-on-rails-3

Given a timestamp, how to get 1 month ago


I'm trying to build a method where I pass a month and can then query for the previous month dynamically.

total_churn(month)
   last_month = month - 1
   companies = Company.where("created_at BETWEEN '#{last_month}' AND '#{month}')
   return companies.count
 end

How do I pass the method 'month' in a way where I can dynamically determine the last month using Ruby on Rails?


Solution

  • My suggestion: accept a date rather than a month.
    total_churn(date)
       month_previous = date - 1.month
       companies = Company.where("created_at BETWEEN ? AND ?, '#{month_previous}', '#{date}')
       return companies.count
    end
    
    Current month:
    Time.now.month
    Date.today.month
    
    Time or day one month ago:
    (Time.now - 1.month).month
    (Date.today - 1.month).month
    
    ...also equivalent to:
    Time.now.month - 1
    Date.today.month - 1
    
    Previous month for any given date:
    @date - 1.month
    

    I would personally build your method to accept a date rather than just a month number. As long as the created_at field is storing dates, you'll need to give the query two dates for it to run, even if those dates are the 1st.