has_one关联无效

时间:2013-08-07 09:26:52

标签: ruby-on-rails activerecord

我有以下ActiveRecord模型:

class User < ActiveRecord::Base
  has_one :faculty
end

class Faculty < ActiveRecord::Base
  belongs_to :head, class_name: 'User', foreign_key: :user_id
end

当我尝试使用与faculty.head的此关联拉取用户时,我得到的记录没有错误,但是当我输入user.faculty时出现错误:

  Faculty Load (1.8ms)  SELECT "faculties".* FROM "faculties" WHERE "faculties"."user_id" = 1 LIMIT 1
ActiveRecord::StatementInvalid: PG::UndefinedFunction: ERROR:  operator does not exist: character varying = integer
LINE 1: ...".* FROM "faculties"  WHERE "faculties"."user_id" = 1 LIMIT ...

我的faculties db架构如下所示:

create_table "faculties", :force => true do |t|
    t.string   "name"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
    t.string   "user_id"
 end

这是一些PG错误吗?

3 个答案:

答案 0 :(得分:2)

由于您的user_idforeign_key,因此integer

t.string   "user_id"

应该是

t.integer   "user_id"

答案 1 :(得分:2)

错误消息显示:

ERROR:  operator does not exist: character varying = integer

这意味着您要尝试比较varchar值(user_id表的faculties字段)和整数值(id的{​​{1}}字段表),这是不允许的。

您必须将外键users定义为user_id

integer

答案 2 :(得分:2)

发生错误是因为您将user_id列作为字符串而不是整数。