Postgres db中strftime的替代方法

时间:2019-01-19 23:08:21

标签: ruby-on-rails ruby postgresql migration to-char

这是我的问题:

This particular table stores information about visits that clients have made so far

“收入”控制者(基本求和)-按天/月/年计

handle_readConnection

从sqlite切换到Postgres使得strftime无法使用-我尝试将其更改为以下内容:

def index
 @days = Visit.select("start_time,SUM(price) as price").group("strftime('%Y-%m-%d', start_time)").where(:start_time => DateTime.now.beginning_of_month..DateTime.now.end_of_month).where(:status => true).order('start_time DESC').all
 @months = Visit.select("start_time,SUM(price) as price").group("strftime('%Y-%m', start_time)").where(:status => true).order('start_time DESC').all
 @years = Visit.select("start_time,SUM(price) as price").group("strftime('%Y', start_time)").where(:status => true).order('start_time DESC').all
 @total = 0
 @years.collect { |x| @total = @total + x.price }
end

但是现在我得到了错误

  

缺少开始时间

在视图中:

 @days = Visit.select("to_char(start_time, 'YYYY-MM-DD'),SUM(price) as price").group("to_char(start_time,'YYYY-MM-DD')").where(:start_time => DateTime.now.beginning_of_month..DateTime.now.end_of_month).where(:status => true).order("to_char(start_time,'YYYY-MM-DD') DESC").all
 @months = Visit.select("to_char(start_time, 'YYYY-MM'),SUM(price) as price").group("to_char(start_time,'YYYY-MM')").where(:status => true).order("to_char(start_time,'YYYY-MM') DESC").all
 @years = Visit.select("to_char(start_time, 'YYYY'),SUM(price) as price").group("to_char(start_time,'YYYY')").where(:status => true).order("to_char(start_time,'YYYY') DESC").all

我不太明白为什么会出现这样的错误。

2 个答案:

答案 0 :(得分:0)

要转换date(而不是datetime),可以使用to_dateto_timestamp https://www.postgresql.org/docs/9.6/functions-formatting.html

答案 1 :(得分:0)

您还可以使用DateTime#iso8601将日期转换为字符串

https://ruby-doc.org/stdlib-2.3.3/libdoc/date/rdoc/DateTime.html#method-i-iso8601