【发布时间】:2019-06-13 18:58:16
【问题描述】:
这是我的问题:
This particular table stores information about visits that clients have made so far
“收入”控制器(基本求和)- 按天/月/年
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
从 sqlite 切换到 Postgres 使 strftime 无法使用 - 我尝试将其更改为如下内容:
@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
但现在我得到错误
缺少开始时间
在视图中:
<table class="table table-hover table-striped table-bordered">
<thead>
<tr>
<th class="text-center">Time period</th>
<th class="text-center">Sum</th>
</tr>
</thead>
<tbody>
<tr>
<th colspan="2">days</th>
</tr>
<% @days.each do |s| %>
<tr>
<td><%= s.start_time.strftime('%d.%m.%Y') %></td>
<td class="text-right"><%= s.price %> eur</td>
</tr>
<% end %>
<tr>
<th colspan="2">months</th>
</tr>
<% @months.each do |s| %>
<tr>
<td><%= s.start_time.strftime('%m.%Y') %></td>
<td class="text-right"><%= s.price %> eur</td>
</tr>
<% end %>
<tr>
<th colspan="2">years</th>
</tr>
<% @years.each do |s| %>
<tr>
<td><%= s.start_time.strftime('%Y') %>r</td>
<td class="text-right"><%= s.price %> eur</td>
</tr>
<% end %>
<tr>
<th class="text-right">All</th>
<td class="text-right"><%= @total %> eur</td>
</tr>
</tbody>
</table>
我真的不明白为什么会出现这样的错误。
【问题讨论】:
-
您不需要在查询中转换
start_time。如果start_time是数据库中的日期时间类型,它将能够将存储的start_time与Date.today进行比较 -
谢谢,成功了!但是现在我无法按月和年分组来工作。
标签: ruby-on-rails ruby postgresql migration to-char