Rails - PG :: DatatypeMismatch:错误

时间:2018-04-24 16:12:38

标签: ruby-on-rails ruby postgresql

所以这是一个非常初学的问题,我收到以下错误。我知道我需要将其转换为字符串类型。我尝试了很多种转换方法,但尚未开始工作。将此字段硬编码为' 2018-01-01'作品。我回来的参数内容是正确的。它是创建此错误的类型。我甚至尝试将其转换为日期类型并测试类型并返回true,但仍然无法成功。如果这是有道理的,请告诉我。

PG::DatatypeMismatch: ERROR:  column "order_date" is of type date but expression is of type integer

我的表达

created_at = (params[:created_at])

尝试了

created_at = (params[:created_at]).to_date
created_at = (params[:created_at]).to_s

我试图从有效负载中获取params[:created_at]并使用以下代码插入到psql中。所以我认为我应该采取创造行动。请让我知道我做错了什么。

def create
  created_at = (params[:created_at])
  puts created_at
  sql = "insert into api.salesorder(site, order_date,sale_type,sales_rep,terms,customer_number) values('WHS',#{created_at},'CUST','HOUSE','PRE','123456')"
  results = ActiveRecord::Base.connection.execute(sql)
end

2 个答案:

答案 0 :(得分:3)

如果您仍然想使用直接SQL(我在Rails中提出建议,因为Rails会为您执行SQL),您需要更改它以用单引号包装日期。

sql = "insert into api.salesorder(site, order_date, sale_type,sales_rep, terms, customer_number) values('WHS','#{created_at}','CUST','HOUSE','PRE','123456')"

更好的解决方案是利用Rails为您完成SQL工作。像这样:

# in app/models/salesorder.rb
class Salesorder < ActiveRecord::Base
end

# in app/controller/salesorder_controller.rb
class SalesorderController < ApplicationController
  def create
    @salesorder = Salesorder.new
    @salesorder.order_date = params[:created_at]
    @salesorder.site = 'WHS'
    @salesorder.sale_type = 'CUST'
    @salesorder.sales_rep = 'HOUSE'
    @salesorder.terms = 'PRE'
    @salesorder.customer_number = '123456'

    if @salesorder.save
      redirect_to @salesorder, notice: 'Salesorder was successfully created.'
    else
      render :new
    end
  end
end

答案 1 :(得分:0)

您可以执行created_at = Date.parse(params[:created_at])之类的操作,但我认为这不是必需的。更多信息可能会有所帮助。你的params是integer类型吗?