错误:运算符不存在:字符变化 = 整数
我面临一个常见问题。我的 Rails 应用程序在我的本地计算机上运行,但部署到 heroku 后崩溃:
<% unless @user.hotels.empty? %>
<% @user.hotels.each do |hotel| %>
<%= "#{hotel.description} #{hotel.name} in #{hotel.city}, #{hotel.country}" %><br />
<% end %>
<% end %>
This is from the heroku log:
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 则不然。这是酒店模型中的外键: 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
....
I face a common problem. My Rails app works on my local machine, but after deploying to heroku it crashes:
<% unless @user.hotels.empty? %>
<% @user.hotels.each do |hotel| %>
<%= "#{hotel.description} #{hotel.name} in #{hotel.city}, #{hotel.country}" %><br />
<% end %>
<% end %>
This is from the heroku logs:
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?
creates the error. I know, sqlite is pretty forgiving, but PostgreSQL is not. This is the foreign key in the hotel model: user_id :integer
Heroku says:
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 }
The migration looks like following:
class CreateHotels < ActiveRecord::Migration
def self.up
create_table :hotels do |t|
t.string :name
t.string :vanity_url
t.integer :user_id
....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当数据库中的外键不是整数时,通常会发生这种情况。
例如:
在本例中,PostgreSQL 期望
user_id
是一个整数,但它几乎看起来像是在告诉您它实际上是一个 varchar。我会尝试删除该列并再次添加它。
This typically happens when the foreign key in the database is not an integer.
For example:
In this case, PostgreSQL expects
user_id
to be an integer, but it almost looks like it's telling you that it was actually a varchar.I would try removing the column and adding it again.