Rails有一些有用的時間助手來爲你查詢的上限和下限。 (beginning_of_month
和end_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
所以你想通過像「一」或類似1的整數字符串? – jstim
我可以通過任何有意義的動作確定1個月前,然後查詢postgres。謝謝 – AnApprentice
該方法不依賴於當前月份。但基於傳遞給該方法的月份。 – AnApprentice