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