如何解决Rails中的“ PG :: CannotCoerce:错误:无法将bigint类型转换为带有时区的时间戳”错误

时间:2019-07-17 08:14:56

标签: ruby-on-rails ruby postgresql group-by ruby-on-rails-5

我想按月显示该组的销售指数,我已经尝试使用过滤器或groupdate gem,但出现此错误

  

PG :: CannotCoerce:错误:无法将类型bigint强制转换为时间戳   时区LINE 1:... NULL)GROUP BY(DATE_TRUNC('month',   (“ sales ..” id“ :: timestam ...                                                                ^:选择“ sales”。*从“ sales”位置(“ sales”。“ id”不为空)   BY(DATE_TRUNC('month',(“ sales ..” id“ :: timestamptz))在时区   '亚洲/曼谷'))时区'亚洲/曼谷'

我也尝试删除time_zone,但出现了这样的错误

  

“ TimeZone []的无效参数::created_at”

class SalesController < ApplicationController
  before_action :set_sale, only: [:show, :edit, :update, :destroy]

  # GET /sales
  # GET /sales.json
  def index
    @sales = Sale.group_by_month(:id, :created_at,format: "%B %Y", time_zone: "Hanoi")
  end

我希望索引按月分组,该时间戳是从带有时间戳类型列的created_at中提取的,例如

January
1, description, total, commission, created_at 
2, description, total, commission, created_at 

February
3, description, total, commission, created_at 

March
4, description, total, commission, created_at

错误:https://i.stack.imgur.com/3dxae.png

源代码:https://i.stack.imgur.com/7AJnY.png

1 个答案:

答案 0 :(得分:0)

首先看起来这行有误:

@sales = Sale.group_by_month(:id, :created_at,format: "%B %Y", time_zone: "Hanoi")

看一下groupdate gem的示例:

User.group_by_week(:created_at, time_zone: "Pacific Time (US & Canada)")

第一个参数(id)过多,您的代码应类似于:

@sales = Sale.group_by_month(:created_at, format: "%B %Y", time_zone: "Hanoi")

这就是为什么实际上收到错误消息“ PG :: CannotCoerce:ERROR:无法将类型bigint强制转换为带有时区的时间戳的原因...”的原因。生成的SQL查询中的"sales"."id"::timestamptz意味着将id列(整数)转换为时间戳记(timestamptz)。

我希望这会有所帮助。