2013-04-02 67 views
1

我试图建立在我经过一个月,然后可以查询前一个月的动态的方法。给定一个时间戳,如何获得1个月前

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

我如何通过“月”的方法,在某种程度上,我可以使用Ruby on Rails的动态确定的最后一个月?谢谢

+0

所以你想通过像“一”或类似1的整数字符串? – jstim

+0

我可以通过任何有意义的动作确定1个月前,然后查询postgres。谢谢 – AnApprentice

+0

该方法不依赖于当前月份。但基于传递给该方法的月份。 – AnApprentice

回答

2
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 

我个人建立你的方法来接受日期而不是一个月的数字。只要created_at字段存储日期,即使这些日期是第一个日期,您仍需要为查询提供两个日期才能运行。

+0

这不是current_month。这个问题是通过一个月,无论任何一个月的期望。 – AnApprentice

+0

@AnApprentice然后用'Date.today'或'Time.now'替换你想要的日期。它仍然会工作。 – sscirrus

1

Rails有一些有用的时间助手来为你查询的上限和下限。 (beginning_of_monthend_of_month中的Time class

此方法也适当地用问号转义而不是字符串插值,这对SQL注入攻击是开放的。

def total_churn(month) 
    companies = Company.where('created_at BETWEEN ? and ?',(Time.now - 1.month).beginning_of_month,(Time.now - 1.month).end_of_month) 
    companies.count 
end 

我也会说这只适用于最近的一年。如果您希望能够查询早期的数据,则可能需要添加一年参数或只需传递一个日期,然后让它使用该日期代替Time.now

# with separate year and month params 
def total_churn(month, year) 
    date = DateTime.parse("#{year}/#{month}/01") 
    companies = Company.where('created_at BETWEEN ? and ?',(date - 1.month).beginning_of_month,(date - 1.month).end_of_month) 
    companies.count 
end 

# with a random date input 
def total_churn(date_in_month) 
    companies = Company.where('created_at BETWEEN ? and ?',(date_in_month - 1.month).beginning_of_month,(date_in_month - 1.month).end_of_month) 
    companies.count 
end 
0

您至少需要2个参数才能完成此操作,一个用于一个月,一个用于一年。这是需要建立你想要的月份。

def total_churn(year, month) 
    date = Date.new year, month 
    one_month_ago = date - 1.month 
    ... 

但是,如果你已经有一个日期对象,那么你可以使用sscirrus的答案。如果日期是在一个字符串,你可能想先分析它(如在您的评论)

def total_churn(date_string) 
    date = Date.parse(date_string) 
    one_month_ago = date - 1.month 
    ... 

>> date_string = '2012-09-01 00:00:00.000000' 
>> total_churn date_string 
相关问题