【问题标题】:Many to one association converting to postres多对一关联转换为 postgres
【发布时间】:2013-07-15 05:20:42
【问题描述】:

我正在将 Rails 应用程序表单 sqlite 转换为 postgres,以便我可以使用 heroku 进行部署。我安装了 postgres 并运行了迁移,但是当我尝试运行查询以查找与房屋关联的所有室友时,出现以下错误

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

此错误源于您在添加房屋后被重定向到创建和管理员的注册视图。这是查看代码:

Extracted source (around line #4):

1: <div class="container">
2:  <div class="row">
3:      <div class="span5 offset3">
4:          <% if current_house.mates.empty? %>
5:              <h2>Add an Administrator</h2>
6:          <% else %>
7:              <h2>Add a New Housemate</h2>

感谢大家的帮助!

【问题讨论】:

标签: ruby-on-rails postgresql


【解决方案1】:

转到add_house_id_to_mates 迁移并将第 3 行从字符串更改为整数。 在此之后,删除 20130628212206_change_type_of_house_id_in_house.rb 迁移。

从零开始运行迁移:

rake db:drop db:create db:migrate

【讨论】:

  • 20130628212206_change_type_of_house_id_in_house.rb ?
【解决方案2】:

您已将 mates 表中的 house_id 列定义为字符类型,它应该是一个整数。一些 RDBMS 可以容忍这一点,但 PostgreSQL 不会。

您应该通过迁移来纠正此问题,并检查数据库架构是否存在其他此类错误。

因为字符列可能包含非数字值,所以在迁移时您必须发出 SQL 语句:

alter table  mates
alter column house_id
type integer using cast(house_id as integer);

【讨论】:

  • 当我运行迁移 change_column :mates, :house_id, :integer 我得到以下错误:PG::Error: ERROR: column "house_id" cannot be cast automatically to type integer HINT: Specify a USING expression to perform the conversion.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-22
  • 1970-01-01
  • 2016-10-06
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多