帮助翻译Rails Sqlite查询到postgresql



我使用以下代码帮助查找当前月份的销售额。我的开发数据库是SQLite,但我使用Heroku生产,它使用PostgreSQL。所以我得到一个strftime函数不存在的错误。我该如何翻译这个,是否有一种方法来翻译它,以便它仍然可以在查询我的开发SQLite数据库时工作?

sales = current_user.location.sales.find( :all,
                                          :conditions => ["strftime('%Y', date) = '?'
                                                          AND strftime('%m', date) = ?",
                                                          Date.today.year,
                                                          Date.today.strftime('%m')],
                                                          :order => "date")

Postgres不支持strftime。您可以在这里找到支持的日期/时间函数列表。

sales = current_user.location.sales.find( :all,
                                          :conditions => ["extract(year from date) = '?'
                                                          AND extract(month from date) = ?",
                                                          Date.today.year,
                                                          Date.today.strftime('%m')],
                                                          :order => "date")

我认为to_timestamp或to_char是您想要查看的类似Postgres函数。这些文档非常简单明了;Postgres数据类型格式化函数

可能比你感兴趣的更多,但我真的建议在本地运行Postgres,如果你做很多工作与Heroku。

如果您想获得当月的销售数据,这可能是一个更合适的、与数据库无关的查询。

current_user.location.sales。(:日期=> (Time.now.beginning_of_month . . Time.now) .order("日期")

最新更新