错误:运算符不存在:character varying = integer

14

我面临一个普遍的问题。我的Rails应用程序在本地机器上运行正常,但是在部署到Heroku后崩溃了:

<% unless @user.hotels.empty? %>
  <% @user.hotels.each do |hotel| %>
    <%= "#{hotel.description} #{hotel.name} in #{hotel.city}, #{hotel.country}" %><br />
  <% end %>
<% end %>

这是来自Heroku日志:

ActionView::Template::Error (PGError: ERROR:  operator does not exist: character varying = integer
LINE 1: SELECT "hotels".* FROM "hotels" WHERE ("hotels".user_id = 1)
                                                                ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
: SELECT "hotels".* FROM "hotels" WHERE ("hotels".user_id = 1)):

@user.hotels.empty? 会出现错误。我知道,sqlite比较宽容,但PostgreSQL不是这样的。这是hotel模型中的外键:user_id :integer

Heroku说:

Make sure the operator is adequate for the data type. ActiveRecord does this automatically when you use an interpolated condition form.

Array conditions:
:conditions => ['column1 = ? AND column2 = ?', value1, value2]

Hash conditions:
:conditions => { :column1 => value1, :column2 => value2 }

迁移过程如下所示:
class CreateHotels < ActiveRecord::Migration
  def self.up
    create_table :hotels do |t|
      t.string :name
      t.string :vanity_url
      t.integer :user_id
      ....

仅从错误信息来看,Postgres 确实将 hotels.user_id 视为 varchar 类型。 - johusman
嗯,在酒店模型中它被设置为整数。 - Lukas Hoffmann
2
在数据库中,user_id 的数据类型是什么?Rails 模型对于此错误消息并不重要。 - user330315
我添加了迁移文件的部分。数据库中的数据类型是整数。 - Lukas Hoffmann
1
请展示数据库中表的定义,例如CREATE TABLE语句。 - user330315
显示剩余2条评论
1个回答

21

通常这种情况发生在数据库中的外键不是整数类型。

例如:

LINE 1: SELECT "hotels".* FROM "hotels" WHERE ("hotels".user_id = 1)
                                                                ^
在这种情况下,PostgreSQL希望user_id是一个整数,但它似乎告诉你它实际上是一个varchar类型的。我建议尝试删除该列并重新添加它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接