2013-04-02 66 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 
相關問題